浅谈Service

一。生命周期:

startService()方式启动,Service是通过接受Intent并且会经历onCreate()和onStart()。当用户在发出意图使之销毁时会经历onDestroy();( onCreate-->onStart-->onDestory )

bindService()方式启动,与Activity绑定的时候,会经历onCreate()和onBind(),而当Activity被销毁的时候,Service会先调用onUnbind()然后是onDestroy()。( onCreate-->onBind -->onUnbind-->onDestory)

二。控制方式:

StartService的控制方式需要使用固定的方法,对Service进行单一的操作。

而BindService由于与Activity绑定,不用考虑其生命周期问题,并且从发送Intent的被动操作,变为可以主动对Service对象进行操作,我们甚至可以建立一个Handler类,对Service进行相关的操作。大大加强了Service的灵活性、可操作性。

总结:对于简单的应用startService()启动方式能带来更少的代码,简单的操作。对于复杂的应用bindService()方式,虽然带来的更多的编码,但同时也带来了更好的可操作性,使其使用起来更像Activity。

 

注意:

Service的生命周期方法比Activity少一些,只有onCreate, onStart, onDestroy 我们有两种方式启动一个Service,他们对Service生命周期的影响是不一样的。

1 通过startService 
Service会经历 onCreate --> onStart 

stopService的时候直接onDestroy,如果是 调用者 直接退出而没有调用stopService的话,Service会一直在后台运行,下次调用者再起来仍然可以stopService。

2 通过bindService 
Service只会运行onCreate, 这个时候 调用者和Service绑定在一起,调用者退出了,Srevice就会调用onUnbind-->onDestroyed,所谓绑定在一起就共存亡了。 

注意:Service的onCreate的方法只会被调用一次,
就是你无论多少次的startService又 bindService,Service只被创建一次。
如果先是bind了,那么start的时候就直接运行Service的onStart方法,
如果先是start,那么bind的时候就直接运行onBind方法。如果你先bind上了,就stop不掉了,
只能先UnbindService, 再StopService,所以是先start还是先bind行为是有区别的。 

 

 

代码:

一。startService -->service内容:

public class MyService extends Service{

    private static final String TAG = "MyService";  
    MediaPlayer player;
    
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override  
    //服务启动前进行的配置
    public void onCreate() {
        Toast.makeText(this, "My Service created", Toast.LENGTH_LONG).show();  
        Log.i(TAG, "onCreate");  
        
        //播放设置
        player = MediaPlayer.create(this, R.raw.music);//提供音乐的位置  
        player.setLooping(false);  //是否循环播放音乐
    }  
  
    @Override  
    //关闭服务
    public void onDestroy() {  
        Toast.makeText(this, "My Service Stoped", Toast.LENGTH_LONG).show();  
        Log.i(TAG, "onDestroy");  
        player.stop();  
    }  
  
    @Override  
    //启动服务
    public void onStart(Intent intent, int startid) {  
        Toast.makeText(this, "My Service Start", Toast.LENGTH_LONG).show();  
        Log.i(TAG, "onStart");  
        player.start();  
    }  
    
}


Activity的内容:

public class Activityone extends Activity{
    
    private static final String TAG = "ServiceDemo"; 
    private Button mybuttonone1;
    private Button mybuttonone2;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_one);
        
        mybuttonone1 = (Button)findViewById(R.id.buttonone1);
        mybuttonone2 = (Button)findViewById(R.id.buttonone2);
                
        //service通过startservice启动服务
        //首先调用mybuttonone1的onclick方法,然后调用myservice的onclick()方法,再然后调用onstart()方法
        mybuttonone1.setOnClickListener(new OnClickListener() {
            
            @Override
            public void onClick(View v) {
                Log.i(TAG, "onClick: starting service");
                startService(new Intent(Activityone.this, MyService.class));
            }
        });
        
        //service通过startservice关闭服务
        //首先调用mybuttonone2的onclick方法,然后调用myservice的onstop()方法
        
        mybuttonone2.setOnClickListener(new OnClickListener() {
            
            @Override
            public void onClick(View v) {
                Log.i(TAG, "onClick: stopping service");  
                stopService(new Intent(Activityone.this, MyService.class));  
            }
        });
        
        mybuttonone1.setOnClickListener(new myclicklistener());
        mybuttonone2.setOnClickListener(new myclicklistener());
        
    }
    
    class myclicklistener implements OnClickListener{
        public void onClick(View src) {  
            switch (src.getId()) {  
                case R.id.buttonone1:  
                    Log.i(TAG, "onClick: starting service");  
                    startService(new Intent(Activityone.this, MyService.class));  
            //startservice  执行的步骤:  onclick()-->onstart()
                    break;  
                case R.id.buttonone2:  
                    Log.i(TAG, "onClick: stopping service");  
                    stopService(new Intent(Activityone.this, MyService.class));  
            //startservice  执行的步骤:  onDestroy()
                    break;  
            }  
        }  
    }
    
}


二。BindService -->service内容:
public class BindService extends Service {
    
    private MyBinder myBinder = new MyBinder();
    private static final String TAG = "BindService";
    private MediaPlayer play;
    
    @Override
    public IBinder onBind(Intent intent) {
            Log.i(TAG, "BindService-->onBind()");
            
            play=MediaPlayer.create(this, R.raw.music);
            play.setLooping(false);
            
            return myBinder;
        }
    
    public class MyBinder extends Binder{
        
        public BindService getService(){
            Log.i(TAG, "BindService-->getService()");
            return BindService.this;
        }
    }
    
    public void MyMethod(){
        Log.i(TAG, "BindService-->MyMethod()");
        play.start();
    }
     
}


Activity的代码:
public class Activitytwo extends Activity{
    
    private Button mybutton1;
    private Button mybutton2;
    private boolean flag;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_two);
        
        mybutton1=(Button)findViewById(R.id.buttontwo1);
        mybutton2=(Button)findViewById(R.id.buttontwo2);
        
        mybutton1.setOnClickListener(new myclicklistener());
        mybutton2.setOnClickListener(new myclicklistener());
        
    }
    
    class myclicklistener implements OnClickListener{

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            switch (v.getId()) {
            case R.id.buttontwo1:
                System.out.println("打开bind1");
                bindService();
                break;
                
            case R.id.buttontwo2:
                System.out.println("关闭bind1");
                unBind();
                break;    
                
            default:
                break;
            }
        }
    }

    private void bindService(){
        System.out.println("打开bind2");
        Intent intent = new Intent(Activitytwo.this,BindService.class);
        bindService(intent, conn, Context.BIND_AUTO_CREATE);
    }
    
    private void unBind(){
        System.out.println("关闭bind2");
        if(flag == true){
            unbindService(conn);
            flag = false;
        }
    }
    
    private ServiceConnection conn = new ServiceConnection() {
        
        @Override
        public void onServiceDisconnected(ComponentName name) {
            System.out.println("关闭bind3");
        }
        
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            System.out.println("打开bind3");
            MyBinder binder = (MyBinder)service;
            BindService bindService = binder.getService();
            bindService.MyMethod();
            flag = true;
        }
    };
    
}


posted @ 2015-11-07 11:03  冷月舞痕  阅读(217)  评论(0编辑  收藏  举报