本地服务(Local)不需要IPC,也不需要AIDL,主进程被Kill后,服务便会终止
远程服务(Remote Service) 独立的进程,因此在Activity所在进程被Kill的时候,该服务依然在运行,不受其他进程影响,并且使用AIDL进行IPC比较麻烦。一般用于系统的Service,这种Service是常驻的。
绑定Service有什么用?
通过Activity来执行Service中的一些功能
绑定服务的步骤:
1.创建一个类,extends Service
2.创建一个Binder对象
3.在onBind()方法中返回Binder对象
public class MyService extends Service { public MyService() { } private DownloadBinder mBinder = new DownloadBinder(); class DownloadBinder extends Binder { public void startDownload() { Log.d("MyService", "startDownload executed"); } public int getProgress() { Log.d("MyService", "getProgress executed"); return 0; } } @Override public IBinder onBind(Intent intent) { return mBinder; } ....
4.主线程中,创建Connection对象,通过downloadBinder对象来调用各种方法
private ServiceConnection connection = new ServiceConnection() { @Override public void onServiceDisconnected(ComponentName name) { } @Override public void onServiceConnected(ComponentName name, IBinder service) { downloadBinder = (MyService.DownloadBinder) service; downloadBinder.startDownload(); downloadBinder.getProgress(); } };
5.主线程中添加启动服务,绑定服务的代码
Intent intent = new Intent(this, DownloadService.class); startService(intent); // 启动服务 bindService(intent, connection, BIND_AUTO_CREATE); // 绑定服务