startService()与bindService()

1.生命周期

    startService():onCreate() -> onStartCommand() -> onStart() (过时方法由onStartCommand()替代) -> onDestroy() 

    bindService():onCreate() -> onBind() -> onServiceConnected() -> onUnbind -> onDestroy()

    onServiceDisconnected只会在Service丢失时才会调用, 通常会在Service所在进程被迫终止时才会调用, 当Service重新运行时会再次调用onServiceConnected方法

2.用startService()启动的service,退出activity()可以不stopService();如果不调用stopService()服务会一直在后台运行

  用bindService()启动的service,退出activity()必须unbindService();如果不调用unbindService(),会报错

 

3.bindService()的代码示例:

  

    

public class MyService extends Service {
    private final String TAG = "MainActivity";
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        Log.e(TAG, "onBind" );
        return new MyBinder();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.e(TAG, "onStartCommand" );
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onStart(Intent intent, int startId) {
        super.onStart(intent, startId);
        Log.e(TAG, "onStart" );
    }

    @Override
    public boolean onUnbind(Intent intent) {
        Log.e(TAG, "onUnbind" );
        return super.onUnbind(intent);
    }

    public String getString() {
        return "你好 哈哈哈";
    }

    public class MyBinder extends Binder{
        MyService getService() {
            return MyService.this;
        }
    }
    
    @Override
    public void onCreate() {
        super.onCreate();
        Log.e(TAG, "onCreate" );
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.e(TAG, "onDestroy" );
    }
}
public class MainActivity extends Activity {

   private MyServiceConnection conn;
   private final String TAG = "MainActivity";

   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      conn = new MyServiceConnection();
      bindService(new Intent(this, MyService.class),conn, Context.BIND_AUTO_CREATE);
   }

   public class MyServiceConnection implements ServiceConnection{
      @Override
      public void onServiceConnected(ComponentName name, IBinder service) {
         MyService myService = ((MyService.MyBinder) service).getService();
         String body = myService.getString();
         Log.e(TAG, "onServiceConnected :"+body );
      }

      @Override
      public void onServiceDisconnected(ComponentName name) {
         Log.e(TAG, "onServiceDisconnected" );
      }
   }

   @Override
   protected void onDestroy() {
      super.onDestroy();
      stopService(new Intent(this, MyService.class));
      unbindService(conn);
   }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值