2.啓動服務按鈕--service

2.啓動服務按鈕android

這個類實現的是第一個按鈕的功能,在這個類中新開了一個線程,並每隔一秒打印出一行日誌app

代碼以下:this

package lovefang.stadyService;
/**引入包*/
 import android.app.Service;// 服務的類
 import android.os.IBinder;
 import android.os.Binder;
 import android.content.Intent;
 import android.util.Log;
/**計數的服務*/
 public class CountService extends Service{
   /**建立參數*/
  boolean threadDisable ;
  int count;
  
  public IBinder onBind(Intent intent){
   return null;
  }
  public void onCreate(){
   super.onCreate();
    /**建立一個線程,每秒計數器加一,並在控制檯進行Log輸出*/
   new Thread(new Runnable(){
    public void run(){
     while(!threadDisable){
      try{
       Thread.sleep(1000);
      }catch(InterruptedException e){
       
      }
      count++;
      Log.v("CountService","Count is"+count);
     }
    }
   }).start();
  }
  public void onDestroy(){
   super.onDestroy();
    /**服務中止時,終止計數進程*/
   this.threadDisable = true;
  }
  public int getConunt(){
   return count;
  }
  class ServiceBinder extends Binder{
   public CountService getService(){
    return CountService.this;
   }
  }
 }
相關文章
相關標籤/搜索