android 筆記(Service)

Servicehtml

 

 

一。Serivce的啓動方式分兩種 前端

 

1.startService。用這種方式啓動的話,負責啓動這個serviceActivity或者其餘組件即便被銷燬了,Service也會繼續在後臺運行,必須得Serivce本身作完任務區去調用stopSelf或者stopService去中止這個Serice。這種方式是Start方式android

 

2.bindService。這種方式要組件去調用BindService去綁定一個Service,這種方式Service的生命週期是知道全部綁定這個service的組件unbind以後纔會銷燬。這種方式稱之爲 Boundapp

 

 

startService調用後會自動調用startCommand,你須要作的工做能夠在這裏寫,例如啓動新線程去執行任務之類的。ide

bindService以後會調用Onbind函數,功能同上,須要本身去重寫,還有就是通訊就是經過這個onbind函數返回的IBinder函數

以上兩種方式能夠一塊兒使用,不是必定要分開。。oop

 

 

 

二.實現Service須要重寫的方法ui

通常來講,實現Service,實現如下幾個方法就好:this

 

onStartCommand()spa

onBind()

onCreate()

onDestroy()

函數名字仍是很是清楚的,具體做用就不說了。

 

三.在manifest裏面加入Service

 

Activity同樣,要使用你本身寫的Service,必須得在manifest裏面註冊

例如

<manifest ... >
  ...
  <application ... >
      <service android:name=".ExampleService" />
      ...
  </application>
</manifest>

 

Service的名字一旦肯定,就不要更改了,由於其餘地方會利用這個名字去訪問Service

值得注意的是,一個service能夠被其餘應用程序去訪問,若是你不想被其餘應用程序訪問,就在文件裏面加入屬性android:exported,而後設置爲False

四.實現Service的兩種方法

實現Service主要有兩種方式:

1.Service

要重寫幾個函數,並且通常工程來講,都要本身建立新線程來執行任務,這些工做都要咱們本身去編寫來作。

代碼以下:

 

public class HelloService extends Service {
  private Looper mServiceLooper;
  private ServiceHandler mServiceHandler;

  // Handler that receives messages from the thread
  private final class ServiceHandler extends Handler {
      public ServiceHandler(Looper looper) {
          super(looper);
      }
      @Override
      public void handleMessage(Message msg) {
          // Normally we would do some work here, like download a file.
          // For our sample, we just sleep for 5 seconds.
          long endTime = System.currentTimeMillis() + 5*1000;
          while (System.currentTimeMillis() < endTime) {
              synchronized (this) {
                  try {
                      wait(endTime - System.currentTimeMillis());
                  } catch (Exception e) {
                  }
              }
          }
          // Stop the service using the startId, so that we don't stop
          // the service in the middle of handling another job
          stopSelf(msg.arg1);
      }
  }

  @Override
  public void onCreate() {
    // Start up the thread running the service.  Note that we create a
    // separate thread because the service normally runs in the process's
    // main thread, which we don't want to block.  We also make it
    // background priority so CPU-intensive work will not disrupt our UI.
    HandlerThread thread = new HandlerThread("ServiceStartArguments",
            Process.THREAD_PRIORITY_BACKGROUND);
    thread.start();
    
    // Get the HandlerThread's Looper and use it for our Handler 
    mServiceLooper = thread.getLooper();
    mServiceHandler = new ServiceHandler(mServiceLooper);
  }

  @Override
  public int onStartCommand(Intent intent, int flags, int startId) {
      Toast.makeText(this, "service starting", Toast.LENGTH_SHORT).show();

      // For each start request, send a message to start a job and deliver the
      // start ID so we know which request we're stopping when we finish the job
      Message msg = mServiceHandler.obtainMessage();
      msg.arg1 = startId;
      mServiceHandler.sendMessage(msg);
      
      // If we get killed, after returning from here, restart
      return START_STICKY;
  }

  @Override
  public IBinder onBind(Intent intent) {
      // We don't provide binding, so return null
      return null;
  }
  
  @Override
  public void onDestroy() {
    Toast.makeText(this, "service done", Toast.LENGTH_SHORT).show(); 
  }
}

 

 

2.IntentService

若是隻是啓動一個線程作一個單獨任務,這個是首選,系統幫你實現好了幾個必須重寫的函數,你只須要作的是事情就是實現一個函數就行:onHandleIntent(intent) 參數是startCommand那裏傳過來的。

看代碼:

public class HelloIntentService extends IntentService {

  /** 
   * A constructor is required, and must call the super IntentService(String)
   * constructor with a name for the worker thread.
   */
  public HelloIntentService() {
      super("HelloIntentService");
  }

  /**
   * The IntentService calls this method from the default worker thread with
   * the intent that started the service. When this method returns, IntentService
   * stops the service, as appropriate.
   */
  @Override
  protected void onHandleIntent(Intent intent) {
      // Normally we would do some work here, like download a file.
      // For our sample, we just sleep for 5 seconds.
      long endTime = System.currentTimeMillis() + 5*1000;
      while (System.currentTimeMillis() < endTime) {
          synchronized (this) {
              try {
                  wait(endTime - System.currentTimeMillis());
              } catch (Exception e) {
              }
          }
      }
  }
}

注意,startCommand返回的值是有用的,決定這個service被系統幹掉後要不要從新啓動,這個值有三個枚舉START_NOT_STICKYSTART_STICKYSTART_REDELIVER_INTENT

五.經過intent來開啓Service

啓動Service就是建立一個intent對象,參數傳進去須要啓動的Service名稱,就能夠啦,調用startService啦,

若是須要Service傳回來一些消息,能夠 用PendingIntent,而後傳給startService用的intent,而後能夠用getBroadcast來獲得消息。 

六.startForeground()來讓service在前端顯示

相似播放器同樣,你想通知欄裏面看到在放什麼歌曲,還有點擊放下一首時,須要調用startForeground()讓service運行在前端

 

Notification notification = new Notification(R.drawable.icon, getText(R.string.ticker_text),
        System.currentTimeMillis());
Intent notificationIntent = new Intent(this, ExampleActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
notification.setLatestEventInfo(this, getText(R.string.notification_title),
        getText(R.string.notification_message), pendingIntent);
startForeground(ONGOING_NOTIFICATION_ID, notification);

 

具體Service的其餘方面能夠去看下官方文檔

相關文章
相關標籤/搜索