android-studio startService服务

    xiaoxiao2025-06-25  4

    .xml

    <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@drawable/ic_launcher_background"> <Button android:id="@+id/btn_start" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_above="@+id/btn_stop" android:layout_centerHorizontal="true" android:layout_marginBottom="90dp" android:background="#B0E0E6" android:onClick="start" android:text="开启服务" android:textColor="#6C6C6C" android:textSize="18sp"/> <Button android:id="@+id/btn_stop" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignLeft="@+id/btn_start" android:layout_alignParentBottom="true" android:layout_alignStart="@+id/btn_start" android:layout_marginBottom="25dp" android:background="#F08080" android:onClick="stop" android:text="关闭服务" android:textColor="#6C6C6C" android:textSize="18sp"/> </RelativeLayout>

    MyService.java

    package com.example.administrator.fuwu; import android.app.Service; import android.content.Intent; import android.os.IBinder; import android.support.annotation.Nullable; import android.util.Log; public class MyService extends Service{ @Nullable @Override public IBinder onBind(Intent intent){ return null; } public void onCreate(){ super.onCreate(); Log.i("StartService","onCreate()"); } public int onStartCommand(Intent intent,int flags,int startId){ Log.i("StartService","onStartCommand()"); return super.onStartCommand(intent,flags,startId); } public void onDestroy(){ super.onDestroy(); Log.i("StartService","onDestroy()"); } }

    MainActivity.java

    package com.example.administrator.fuwu; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button start = (Button) findViewById(R.id.btn_start); Button stop = (Button) findViewById(R.id.btn_stop); } public void start(View view){ Intent intent = new Intent(this,MyService.class); startService(intent); } public void stop(View view){ Intent intent = new Intent(this,MyService.class); stopService(intent); } }
    最新回复(0)