Service

一.bindService和startService的区别:


执行startService时,Service会经历onCreate->onStartCommand。当执行stopService时,直接调用onDestroy方法。调用者如果没有stopService,Service会一直在后台运行,下次调用者再起来仍然可以stopService。

 

执行bindService时,Service会经历onCreate->onBind。这个时候调用者和Service绑定在一起。调用者调用unbindService方法或者调用者Context不存在了(如Activity被finish了),Service就会调用onUnbind->onDestroy。这里所谓的绑定在一起就是说两者共存亡了。

 

多次调用startService,该Service只能被创建一次,即该Service的onCreate方法只会被调用一次。但是每次调用startService,onStartCommand方法都会被调用。Service的onStart方法在API 5时被废弃,替代它的是onStartCommand方法。

 

第一次执行bindService时,onCreate和onBind方法会被调用,但是多次执行bindService时,onCreate和onBind方法并不会被多次调用,即并不会多次创建服务和绑定服务。

 

生命周期示意图:


二.Service的方法:
onBind(), onCreate()、onStartCommand()和onDestroy()这三个方法,它们是每个服务中最常用到的三个方法了。其中onCreate()方法会在服务创建的时候调用,onStartCommand()方法会在每次服务启动的时候调用,onDestroy()方法会在服务销毁的时候调用。

调用bindService绑定服务后,则不会调用onStartCommand().unbindService调用后onDestroy()销毁服务.


*Android的四大组件,Activity,BroadcaseReceiver,ContextProvider,Service都需要在AndroidManifest.xml中注册

 

三.startService用法:

 

@Override
protected void onCreate(Bundle savedInstanceState) {
    ......
    intent = new Intent(this, MyService.class);
        startService(intent); // 如果服务没有创建,将执行onCreate->onStartCommand(),如果有创建将直接执onStartCommand()
    ......
}


@Override
protected void onDestroy() {
    stopService(intent);
        super.onDestroy();
}

 

四.bindService用法

Service:

public class MyService extends Service {
    private PlayBinder playBinder;
    class PlayBinder extends Binder{
        ....定义方法供Activity调用
        public void function(){
        
        }
        ....
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return playBinder;
    }

    @Override
    public void onCreate() {
        playBinder = new PlayBinder();
        super.onCreate();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }
}

 

Activity:

public class MainActivity extends Activity {

    ....
    MyService.PlayBinder playBinder;
    Intent intent;
    ....

    ServiceConnection conn = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            playBinder = (MyService.PlayBinder)service;
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    };

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

    protected void myClick(View v){
        if(v.getId() == R.id.btn1){
            playBinder.function();
        }
    }

    @Override
    protected void onDestroy() {
        unbindService(conn);
        super.onDestroy();
    }
}

 

posted @ 2017-04-23 09:25  rorshach  阅读(293)  评论(0编辑  收藏  举报