一看就懂的Service生命週期

今天閒着無事,就寫了一個生命週期,一看就明白了大家。首先創建——開始——銷燬,整個流程。真的非常簡單,先讓大家看一下圖先。



根據上面的按鈕所得到方法,大家可以在LogCat中增加一個標籤,立即可以看到

 

  1. package com.smart.service; 
  2.  
  3. import android.app.Service; 
  4. import android.content.Intent; 
  5. import android.os.IBinder; 
  6. import android.util.Log; 
  7.  
  8. public class ServiceLeft extends Service { 
  9.     private static final String TAG="ServiceLeft"
  10.      
  11.      
  12.     @Override 
  13.     public IBinder onBind(Intent arg0) { 
  14.         // TODO Auto-generated method stub 
  15.         return null
  16.     } 
  17.  
  18.     @Override 
  19.     public void onCreate() { 
  20.         ////進行創建 
  21.         Log.i(TAG, "onCreate"); 
  22.         super.onCreate(); 
  23.     } 
  24.  
  25.     @Override 
  26.     public void onDestroy() { 
  27.          
  28.         //進行銷燬 
  29.         Log.i(TAG, "onDestroy"); 
  30.         super.onDestroy(); 
  31.     } 
  32.  
  33.     @Override 
  34.     public void onStart(Intent intent, int startId) { 
  35.         //進行開始 
  36.         Log.i(TAG, "onStart"); 
  37.         super.onStart(intent, startId); 
  38.     } 
  39.  
  40. package com.smart.service; 
  41.  
  42. import android.app.Activity; 
  43. import android.content.Intent; 
  44. import android.os.Bundle; 
  45. import android.view.View; 
  46. import android.view.View.OnClickListener; 
  47. import android.widget.Button; 
  48.  
  49. public class Main extends Activity implements OnClickListener { 
  50.     private Button llbstatr; 
  51.     private Button llbstop; 
  52.     private Intent serviceIntent; 
  53.  
  54.     @Override 
  55.     public void onCreate(Bundle savedInstanceState) { 
  56.         super.onCreate(savedInstanceState); 
  57.         setContentView(R.layout.main); 
  58.  
  59.         llbstatr = (Button) findViewById(R.id.llbstart); 
  60.         llbstop = (Button) findViewById(R.id.llbstop); 
  61.         llbstatr.setOnClickListener(this);// 綁定器 
  62.         llbstop.setOnClickListener(this); 
  63.         serviceIntent = new Intent(this, ServiceLeft.class);// 跳轉ServiceLeft生命週期並且調用方法 
  64.  
  65.     } 
  66.  
  67.     @Override 
  68.     public void onClick(View v) { 
  69.         // 根據按鈕,觸發事件 
  70.         switch (v.getId()) { 
  71.         case R.id.llbstart: 
  72.             startService(serviceIntent); 
  73.             break
  74.         case R.id.llbstop: 
  75.             stopService(serviceIntent); 
  76.             break
  77.  
  78.         } 
  79.  
  80.     } 
  81.  

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章