读前思考
- Service的生命周期?
- Service的启动方式?区别?
- Serivice如何去Activity之间通信?
- 如何跨进程调用Service?
- Service如何进行耗时操作?
- 前台服务是什么?和普通服务的不同?如何去开启一个前台服务?
本地服务(LocalService)
调用者和service在同一个进程里,所以运行在主进程的main线程中。所以不能进行耗时操作,可以采用在service里面创建一个Thread来执行任务。service影响的是进程的生命周期,讨论与Thread的区别没有意义。
任何 Activity 都可以控制同一 Service,而系统也只会创建一个对应 Service 的实例。
创建服务
- 创建一个类继承Service,重新onBind();
public class TestService extends Service {
public static final String TAG = "TestService";
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.e(TAG,"onStartCommand");
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onCreate() {
super.onCreate();
Log.e(TAG,"onCreate");
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
Log.e(TAG,"onBind");
return null;
}
- 在清单文件中注册Service
<service android:name=".TestService"/>
启动服务
启动服务有两种方式:startService()和bindService();
startService()
这种方式,服务启动后,服务与启动者没有关系,启动者退出了,服务依旧在后台运行,启动者无法调用服务中的方法。
开启服务:
Intent intent = new Intent(this,TestService.class);
startService(intent);
关闭服务:
Intent intent = new Intent(this,TestService.class);
stopService(intent);
生命周期:
com.study.hdq.componentdemo E/TestService: onCreate
com.study.hdq.componentdemo E/TestService: onStartCommand
com.study.hdq.componentdemo E/TestService: onDestroy
bindService()
绑定服务开启服务,启动者挂了,服务挂了,启动者可以调用服务中的方法。
//开启服务
Intent intent = new Intent(this,TestService.class);
bindService(intent,connection,BIND_AUTO_CREATE);
//解绑服务
unbindService(connection);
生命周期:
com.study.hdq.componentdemo E/TestService: onCreate
com.study.hdq.componentdemo E/TestService: onBind
com.study.hdq.componentdemo E/TestService: onUnbind
com.study.hdq.componentdemo E/TestService: onDestroy
一个 Activty 先 start 一个 Service 后,再 bind 时会回调 onBind( ) 方法,不会调用 onCreate( ) 方法,因为服务已经启动了。
Service和Activity之间的通信
方式一:广播
这种方式比较简单,用 Android 四大组件之一的广播即可实现通信。
方式二:针对 bindService( ) 启动方式的通信
- 在 Service 中创建类继承 Binder,并在其中编写需要 Activity 调用的方法。
public class MyBinder extends Binder{
public void sendMsg(){
Log.e(TAG,"调用了TestService中的sendMsg()");
}
}
- 在 Service 中创建上述类的对象。
private MyBinder binder = new MyBinder();
- 在 Service 中的 onBind( ) 方法中返回创建的对象。
@Nullable
@Override
public IBinder onBind(Intent intent) {
Log.e(TAG,"onBind");
return binder;
}
- 在 Activity 中创建 ServiceConnection 类,并重写它的 onServiceConnected( ) 和 onServiceDisconnected( ) 方法,并将 onServiceConnected( ) 方法中的 IBinder 类型的对象强转为 Service 中类的类型,之后就可以调用其中的方法进行通信了。
ServiceConnection connection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
TestService.MyBinder binder = (TestService.MyBinder) service;
binder.sendMsg();
}
@Override
public void onServiceDisconnected(ComponentName name) {
}
};
IntentService
IntentService是专门用来解决Service中不能执行耗时操作这一问题的,创建一个IntentService也很简单,只要继承IntentService并覆写onHandlerIntent函数,在该函数中就可以执行耗时操作了
网友评论