Service解析

Service解析:

  运行service有如下两种方式:

   StartService() 访问者退出,service仍然运行; BindService() 访问者与service绑定,访问者退出,service就会终止。

   首次调用startService()启动一个service

 onCreate()-> onStartCommand()-> onStart()   再次启动: onStartCommand()-> onStart()

调用stopService()结束Service()回调onDestory()方法

 

BindService()

 Service类中必须实现如下方法,绑定Service时回调该方法

  

    public IBinder onBind(Intent intent) {  
        Log.i(TAG, "onBind called.");  
            return new Binder() {};  
    }  

BindService()的调用顺序:bindService(Intent service, ServiceConnection conn, int flags)

 onCreate()->onBind() 

 UnBindService()的调用顺序: onUnbind() –> onDestory()

UI线程通过Service调用如下两种方法,创建和启动Service:

 

1.    /** 
2.         * 启动服务 
3.         * @param view 
4.         */  
5.        public void start(View view) {  
6.            Intent intent = new Intent(this, MyService.class);  
7.            startService(intent);  
8.        }  
9.          
10.        /** 
11.         * 绑定服务 
12.         * @param view 
13.         */  
14.        public void bind(View view) {  
15.            Intent intent = new Intent(this, MyService.class);  
16.            bindService(intent, conn, Context.BIND_AUTO_CREATE);  
17.        }  

 

posted @ 2015-10-17 11:53  岁月长衣衫薄  阅读(305)  评论(0编辑  收藏  举报