Android四大组件之Service --- 如何启动和停止Service?

时间:2022-06-29 07:05:55

启动和停止方法主要是通过Intent来实现

以上一篇中的ServiceTest项目为例来启动和停止MyService这个服务

首先修改activity_main.xml中的代码,如下所示:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
//添加两个按钮分别用来启动和停止服务
<Button
android:id="@+id/start_service"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Start Service" />

<Button
android:id="@+id/stop_service"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Stop Service" />

</LinearLayout>

然后修改MainActivity中的代码,如下所示:
public class MainActivity extends AppCompatActivity implements View.OnClickListener {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button startService = (Button) findViewById(R.id.start_service);
Button stopService = (Button) findViewById(R.id.stop_service);
startService.setOnClickListener(this);
stopService.setOnClickListener(this);
}

@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.start_service:
Intent startIntent = new Intent(this, MyService.class);
startService(startIntent); // 启动服务
break;
case R.id.stop_service:
Intent stopIntent = new Intent(this, MyService.class);
stopService(stopIntent); // 停止服务
break;
default:
break;
}
}

}

注意,startService() 和 stopService()都是定义在Context类中的,所以我们在活动中可以直接调用它们。
在上面这个例子中,只要没有点击stop service按钮,Service会一直处于运行状态。那么服务器可以自己停下来吗?
答案是肯定的,只要在MyService的任何一个位置调用stopSelf()方法即可。

优化: 如何证实服务已经成功启动/停止了呢?
最简单的方法是在MyService的几个方法中加入打印日志:
public class MyService extends Service {

...

@Override
public void onCreate() {
super.onCreate();
Log.d("MyService", "onCreate executed");
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d("MyService", "onStartCommand executed");
return super.onStartCommand(intent, flags, startId);
}

@Override
public void onDestroy() {
super.onDestroy();
Log.d("MyService", "onDestroy executed");
}
}