Service启动方式(主要是1,2两种):
1、startService启动 :主要用于启动服务执行后台任务,不进行通信。停止服务使用stopService;
Intent startIntent =new Intent(MainActivity.this,MyService.class);
startService(startIntent);
2、bindService 启动 :该方法启动的服务可以进行通信。
private ServiceConnection connection=new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
downloadBinder=(MyService.DownloadBinder)service;
downloadBinder.startDownload();
downloadBinder.getProgress();
}
@Override
public void onServiceDisconnected(ComponentName componentName) {
}
};
Intent bindIntent=new Intent(this,MyService.class);
bindService(bindIntent,connection,BIND_AUTO_CREATE)// 绑定MainActivity和MyService
Android中bindService的使用及Service生命周期_孙群-CSDN博客_android中bindservice
使用IntentService
Service中的代码都是默认运行在主线程当中,运用Android多线程编程的技术,在Service的每个具体的方法里开启一个子线程,在这里处理耗时的逻辑
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
new Thread(new Runnable() {
@Override
public void run() {
//处理具体的逻辑
stopSelf();// 调用stopSelf()方法让一直处于运行状态的服务停止下来
}
}).start();
Log.d("MyService", "onStartCommand executed");
return super.onStartCommand(intent, flags, startId);
}
调用stopService()或stopSelf()方法,使Service在执行完毕后自动停止的功能。
使用IntentService类,为了可以简单地创建一个异步的、会自动停止的Service
public class MyIntentService extends IntentService {
public MyIntentService(){
super("MyIntentService");
}
@Override
public void onDestroy() {
super.onDestroy();
Log.d("MyIntentService","onDestroy executed");
}
@Override
protected void onHandleIntent(@Nullable Intent intent) {
Log.d("MyIntentService","Thread id is "+Thread.currentThread().getId());
}
}
首先要求必须先调用父类的构造函数,并传入一个字符串,这个字符串可以随意指定,只在调试的时候有用。子类中实现onHandlerIntent()这个抽象方法,在这个方法中可处理一些耗时的逻辑,方法在子线程中,通过打当前线程名证实。
IntentService特性,这个Service运行结束自动停止,重写onDestroy()方法,日志证实。
case R.id.start_intent_service:
// 打印主线程的id
Log.d("MainActivity","Thread id is "+Thread.currentThread().getId());
Intent intentService=new Intent(this,MyIntentService.class);
startService(intentService);
注册
<service
android:name=".MyService"
android:enabled="true"
android:exported="true">
</service>