Service的使用

时间:2023-12-01 11:22:26

一、Service的适用范围

  1.本地服务(Local Service): 应用程序的内部(单个APP)

    startServcie  stopService  stopSelf  stopSelfResult

    bindService  unbindService

  2.远程服务 (Remote  Service) :  Android系统内部应用程序之间(多个APP)

    定义IBinder的接口

  3.Service的生命周期

    Service的使用

  4.startService和bindService的各自特点

    Service的使用

    
   //通过ServiceConnect对象的相关方法可以得到Service的对象
    ServiceConnection conn = new ServiceConnection() {
    @Override
    public void onServiceConnected(ComponentName name, IBinder binder) {
    service = ((MyBinderService.MyBind)binder).getService();
    }     //通过Ibinder接口实例返回给ServiceConnect对象给启动源
    public class MyBinderService extends Service {
    private String TAG = "info";     public class MyBind extends Binder{
    public MyBinderService getService(){
    return MyBinderService.this;
    }
    }
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
    Log.i(TAG, "MyBinderService-onBind: ");
    return new MyBind();
    }
    intent = new Intent(MainActivity.this , MyBinderService.class);
    bindService(intent, conn(ServiceConnect), Service.BIND_AUTO_CREATE);