一、创建Service
自定义类继承Service类,并在AndroidManifest中注册:
<application …>
<service
android:name=".MyService"
android:enabled="true"
android:exported="true" />
</application>
自定义Service常用的重写方法以及作用:
方法名 | 作用 |
---|---|
onCreate | 服务创建时调用 |
onStartCommand | 服务启动时调用 |
onDestory | 服务销毁时调用 |
onBind | 用于Service和Activity之间的通信,让Activity可以控制运行中的Service |
启动和停止Service:
Intent startIntent = new Intent(this, MyService.class);
startService(startIntent);
Intent stopIntent = new Intent(this, MyService.class);
stopService(stopIntent);
或者可以在Service中通过调用stopSelf();
方法来停止该服务
二、Activity和Service进行通信的方法
虽然说onBind方法用于和service进行通信,但是单纯只是onBind方法是无法完成这个功能的。
基本的通信构建过程:
- 在自定义的Service类中自定义一个Binder内部类,并获取一个自定义内部类的对象。自定义类中的方法将会在Activity中调用,即这个Service提供给Activity的控制方法都需要在这里书写。而在这里获取到的自定义类对象将作为onBind方法的返回值,在Activity和Service绑定时作为参数之一传入到onServiceConnected方法中。
//获取一个自定义类对象作为oonBind方法的返回值
private DownloadBinder mBinder = new DownloadBinder()