Service的生命周期

Service是四大組件之一:主要用於在後臺執行一些比較耗時的操作,如音樂播放,數據下載等…
Service分為兩種:startService和bindService
 
下面分別介紹兩種Service:
1、Started:
A service is "started" when an application component (such as an activity) starts it by calling startService(). Once started, a service can run in the background indefinitely, even if the component that started it is destroyed. Usually, a started service performs a single operation and does not return a result to the caller. For example, it might download or upload a file over the network. When the operation is done, the service should stop itself.
 
解釋:這種Service通過調用startService()方法啟動,一旦啟動,調用者和服務之間沒有任何關系,即使調用者不存在瞭,服務仍然會執行
2、Bound:
A service is "bound" when an application component binds to it by calling bindService(). A bound service offers a client-server interface that allows components to interact with the service, send requests, get results, and even do so across processes with interprocess communication (IPC). A bound service runs only as long as another application component is bound to it. Multiple components can bind to the service at once, but when all of them unbind, the service is destroyed
 
解釋:這種Service通過調用bindService啟動,這種Service可以和調用者進行交互,一旦調用者調用unbindService,那麼該服務就會停止
 
 
下面簡單的介紹第一種Service的使用:
使用第一種Service可以繼承IntentService,也可以繼承Service,代碼如下:
[java]
public class MyIntentService extends IntentService 

    private int count=0; 
 
    public MyIntentService() 
    { 
        super("intentService"); 
        // TODO Auto-generated constructor stub 
    } 
 
    @Override 
    protected void onHandleIntent(Intent intent) 
    { 
        // TODO Auto-generated method stub 
        System.out.println("onHandleIntent 執行"+count++); 
        try 
        { 
            Thread.sleep(1000); 
        } catch (InterruptedException e) 
        { 
            // TODO Auto-generated catch block 
            e.printStackTrace(); 
        } 
        System.out.println("Service Thread=====>"+Thread.currentThread().getId()); 
 
    } 
 

 
[java]
public class MyService extends Service 

     
     
    private int count=0; 
 
    @Override 
    public IBinder onBind(Intent intent) 
    { 
        // TODO Auto-generated method stub 
        return null; 
    } 
 
    @Override 
    public void onCreate() 
    { 
        // TODO Auto-generated method stub 
        super.onCreate(); 
        System.out.println("Service Thread=======>"+Thread.currentThread().getId()); 
        System.out.println("onCreate()"); 
    } 
 
    @Override 
    public void onDestroy() 
    { 
        // TODO Auto-generated method stub 
        super.onDestroy(); 
        System.out.println("onDestroy()"); 
    } 
 
    @Override 
    public int onStartCommand(Intent intent, int flags, int startId) 
    { 
        // TODO Auto-generated method stub 
         
        new Thread() 
        { 
 
            @Override 
            public void run() 
            { 
                // TODO Auto-generated method stub 
                System.out.println("onStartCommand()"+count++); 
                try 
                { 
                    Thread.sleep(2000); 
                } catch (InterruptedException e) 
                { 
                    // TODO Auto-generated catch block 
                    e.printStackTrace(); 
                } 
                System.out.println("Service Thread=========>"+Thread.currentThread().getId()); 
                 
            } 
             
        }.start(); 
         
        return Service.START_STICKY; 
         
    } 
     
     
 

當我們使用第一種方式時,隻需要改寫protected void onHandleIntent(Intent intent),其他的生命周期函數父類已經幫我們完成好瞭,在這裡要說明一點:
Service是和調用者運行在同一個線程裡面的,但是IntentService中,已經幫我們創建瞭一個線程,並且該線程有一個消息隊列,當我們多次啟動同一個線程時,將這多次啟動放入消息隊列中,依次執行。
啟動第一種Service的運行結果為(啟動三次,發現線程id是同一個)
 

如果使用第二種方式,那麼最好自己創建一個線程,不然可能會出現ANR異常。(3次啟動服務)

仔細觀察:OnCreate隻執行一次,OnStartCommand執行瞭3次,
 
下面用普通的Service來模擬IntentService
代碼如下:
[java] 
public class MyService2 extends Service 

    private Looper looper; 
    private HandlerThread thread; 
    private Handler handle; 
     
 
    @Override 
    public IBinder onBind(Intent intent) 
    { 
        // TODO Auto-generated method stub 
        return null; 
    } 
 
    @Override 
    public void onCreate() 
    { 
        // TODO Auto-generated method stub 
        super.onCreate(); 
        thread=new HandlerThread("handlerthread"); 
        thread.start(); 
        looper=thread.getLooper(); 
        handle=new Handler(looper) 
        { 
            @Override 
            public void handleMessage(Message msg) 
            { 
                // TODO Auto-generated method stub 
                 
                System.out.println("執行。。。"); 
                try 
                { 
                    Thread.sleep(1000); 
                } catch (InterruptedException e) 
                { 
                    // TODO Auto-generated catch block 
                    e.printStackTrace(); 
                } 
                System.out.println("handler Thread====>"+Thread.currentThread().getId()); 
                stopSelf(msg.arg1); 
            } 
        }; 
         
    } 
 
    @Override 
    public int onStartCommand(Intent intent, int flags, int startId) 
    { 
        // TODO Auto-generated method stub 
        Message msg=handle.obtainMessage(); 
        msg.arg1=startId; 
        msg.sendToTarget(); 
        return super.onStartCommand(intent, flags, startId); 
    } 
 
     
     
 

總結一下第一種方式Service的生命周期:
1、當服務第一次啟動時,首先執行onCreate,然後onStartCommand,如果服務停止 則執行onDestroy
2、當服務多次啟動,則隻會執行onStartCommand,不會執行onCreate,停止執行onDestroy
 
至於第二種Servive,我就不再詳細敘述瞭,我隻把結論拿出來,如果有不懂的,歡迎留言:
1、當第一次啟動時,首先執行OnCreate,然後執行onBind,最後執行onDestroy
2、當多次啟動服務時,onCreate和onBind都不會執行,最後執行onDestroy
 

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。