1. 创建一个service:
public class MyService extends Service {}
2.在清单中申明service
<application>
<application>
<service
android:name=".MyService"
android:enabled="true"
android:exported="true">
</service>
</application>
android:name=".MyService"
android:enabled="true"
android:exported="true">
</service>
</application>
3.调用service
Intent intent=new Intent(this,MyService.class);
this.startService(intent);
this.startService(intent);
4.停止service
this.stopService(intent);或者 stopSelf
执行流程:
onCreate() //启动服务的时候执行,只执行一次
onStartCommand(Intent intent, int flags, int startId) //每次调用startService
onStartCommand(Intent intent, int flags, int startId) //每次调用startService
onDestroy() //调用stoService 执行