Service (服务)是一个长期运行在后台的用户组件,没有用户界面。即使切换到另一个应用程序,服务也可以在后台运行,因此服务更适合执行一段时间而又不需要显示界面的后台操作。例如下载数据、播放音乐等。
服务的创建
服务的创建与广播接收者类似,同样在程序包名上点击右键选择【New】——>【Service】——>【Service】选项,在弹出窗口中输入服务的名称即可完成创建。
服务创建完成后,Android Studio会自动在AndroidManifest.xml
中对服务进行注册
在上述代码中,创建MyService继承了Service,默认包含一个构造方法和一个onBand() 方法。
onBand() 方法用于绑定一个服务,并返回一个 IBinder 对象。
<service
android:name=".MyService"
android:enabled="true"
android:exported="true">
</service>
name:服务的路径
enabled:系统能否实例化该组件
exported:该服务能否被其他应用程序调用或交互
服务的生命周期
服务的启动方式有两种,分别是 startService()方法 和 bindService()方法/启动方式不同,生命周期也是不同的。
当通过startService()方法启动服务时,需要自身调用stopSelf()方法或者其他组件调用stopService()方法时服务才能停止。
当使用bindService()方法启动服务时,需要调用onUnbind()方法解除绑定之后才会被销毁。
接下来简单介绍一下服务生命周期中的这些方法,具体如下。
- onCreate():第一次创建服务时执行的方法;
- onDestory(): 服务被销毁时执行的方法;
- onStartCommand():客户端通过调用startService()方法启动服务时执行该方法;
- onBind():客户端通过调用bindService()方法启动服务时执行该方法;
- onUnbind():客户端调用unBindService()断开服务绑定时执行的方法。
从图可以看出,当通过startService()方法启动服务时,执行的生命周期方法为onCreate()、
onStartCommand(),然后服务处于运行状态,直到自身调用stopSelf()方 法或者其他组件调用
stopService()方法时服务停止,最终被系统销毁。
当使用bindService()方法启动服务时,执行的生命周期方法为onCreate()、 onBind(), 然后服务处于运行状态,直到调用unBindService()方法时,服务被解绑调用onUnbind()方法,最终被销毁。
服务的启动方式
StartService 方式启动
- startService()方法启动服务,服务会长期的在后台运行,并且服务的状态与开启者的状态没有关系,即使启动服务的组件已经被销毁,服务会依旧运行。
创建一个 StartService 并重写方法
public class StartService extends Service {
public StartService() {
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
Log.i("StartService","onCreate()");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i("StartService","onStartCommand()");
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
super.onDestroy();
Log.i("StartService","onDestroy()");
}
}
MainActivity 调用
public class MainActivity extends AppCompatActivity {
private Button btn_start;
private Button btn_stop;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn_start = findViewById(R.id.btn_start);
Button btn_stop = findViewById(R.id.btn_stop);
}
/**
* 开启服务的方法
*/
public void start(View view){
Intent intent = new Intent(this,StartService.class);
startService(intent);
}
/**
* 关闭服务的方法
*/
public void stop(View view){
Intent intent = new Intent(this,StartService.class);
stopService(intent);
}
}
bindService方式启动
通过bindService()方法启动服务时,服务会与组件绑定。当调用onUnbind()方法时,这个服务就会被销毁。
BindService
public class BindService extends Service {
// 创建服务的代理,调用服务中的方法
class MyBinder extends Binder{
public void callMethodIn