說說在Android如何使用服務(Service)的方法

Android 服務(Service)適合執(zhí)行那些不需要和用戶交互而且還要求長期運行的任務。

網(wǎng)站建設哪家好,找創(chuàng)新互聯(lián)!專注于網(wǎng)頁設計、網(wǎng)站建設、微信開發(fā)、小程序制作、集團企業(yè)網(wǎng)站建設等服務項目。為回饋新老客戶創(chuàng)新互聯(lián)還提供了涼城免費建站歡迎大家使用!

服務的運行不依賴于任何用戶界面,即使 APP 被切換到后臺,或者打開了另外一個 APP,服務仍然能夠保持正常運行。

但是當某個 APP 進程被殺掉時,那么這個 APP 所創(chuàng)建的所有服務也就停止咯。

另外,服務本身并不會自動開啟線程,服務代碼默認是運行在主線程中的。所以如果需要執(zhí)行的業(yè)務邏輯耗時長,那么為了防止主線程被阻塞,我們必須在服務內(nèi)部創(chuàng)建子線程來執(zhí)行這些業(yè)務邏輯。

1 定義服務

在 Android Studio 中可以通過 File→New→Service→Service 來創(chuàng)建服務:

說說在Android如何使用服務(Service)的方法

在彈出的對話框中配置服務:

說說在Android如何使用服務(Service)的方法

在此配置服務名。下面兩個配置項說明如下:

* Exported:是否允許除了當前程序之外的其他程序訪問這個服務。(默認勾選)

* Enabled:是否啟用這個服務 。 (默認勾選)

public class FirstService extends Service {

 private static final String TAG = "FirstService";

 @Override
 public void onCreate() {
  super.onCreate();
  Log.d(TAG, "onCreate");
 }

 @Override
 public int onStartCommand(Intent intent, int flags, int startId) {
  Log.d(TAG, "onStartCommand");
  return super.onStartCommand(intent, flags, startId);
 }

 @Override
 public void onDestroy() {
  super.onDestroy();
  Log.d(TAG, "onDestroy");
 }

 public FirstService() {
 }

 @Override
 public IBinder onBind(Intent intent) {
  // TODO: Return the communication channel to the service.
  throw new UnsupportedOperationException("Not yet implemented");
 }
}

創(chuàng)建好后的服務繼承自 Service,并且需要實現(xiàn) onBind() 方法。我們在此還重寫了以下幾個方法:

方法說明
void onCreate()服務創(chuàng)建時調(diào)用該方法。
onStartCommand(Intent intent, int flags, int startId)每次服務啟動時調(diào)用該方法。
void onDestroy()服務銷毀時調(diào)用該方法。

我們還在這些方法中加入了日志,便于觀察運行結(jié)果。

此外,在此類的任何位置調(diào)用 stopSelf() 方法,服務就會自行停止。

定義好服務后,需要在 AndroidManifest.xml 中注冊服務(如果用的是 Android Studio,那么這一步它已經(jīng)幫我們做啦):

<service
 android:name=".FirstService"
 android:enabled="true"
 android:exported="true"></service>

2 啟動或停止服務

借助 Intent,我們就可以控制服務的啟動與停止啦O(∩_∩)O哈哈~

final Context context = this;
findViewById(R.id.start_service).setOnClickListener(new View.OnClickListener() {
 @Override
 public void onClick(View v) {
  //啟動服務
  startService(new Intent(context, FirstService.class));
 }
});
findViewById(R.id.stop_service).setOnClickListener(new View.OnClickListener() {
 @Override
 public void onClick(View v) {
  //停止服務
  stopService(new Intent(context, FirstService.class));
 }
});

這里的 startService()stopService() 方法都是定義在 Context 類中,所以在活動類中可以直接調(diào)用。

執(zhí)行結(jié)果:

D/FirstService: onCreate   D/FirstService: onStartCommand D/FirstService: onDestroy

**注意:**onCreate() 在第一次創(chuàng)建服務時被調(diào)用,而 onStartCommand() 會在每次啟動服務時被調(diào)用。

服務啟動后,可以在 Android 的 Settings → Developer opinions → Running services 中發(fā)現(xiàn)它:

說說在Android如何使用服務(Service)的方法

點擊 APP 后,可以看到服務詳情:

說說在Android如何使用服務(Service)的方法

如果找不到 Developer opinions 選項,請先在 Android 的 Settings → About emulated device → 多次點擊 Build number 就可以開啟開發(fā)者模式啦:

說說在Android如何使用服務(Service)的方法

3 活動控制服務

活動是通過實現(xiàn) ServiceConnection 接口來與服務建立連接的,它包含以下兩個方法:

方法說明
onServiceConnected(ComponentName name, IBinder service)服務綁定后調(diào)用該方法。
onServiceDisconnected(ComponentName name)服務解綁后調(diào)用該方法。

而服務是通過實現(xiàn) IBinder onBind(Intent intent) 方法來轉(zhuǎn)換為 onServiceConnected() 方法所需要的 IBinder 型的 service 參數(shù)的。

首先,我們修改服務類:

public class FirstService extends Service {
 class CustomBinder extends Binder {

  public void init(){
   Log.d(TAG, "init CustomBinder");
  }

 }

 @Override
 public IBinder onBind(Intent intent) {
  return new CustomBinder();
 }
}

這里,我們定義了一個內(nèi)部類 CustomBinder,里面實現(xiàn)了一個簡單的初始化方法。然后在 onBind() 方法中返回它的實例。

接著,我們修改活動類,創(chuàng)建 ServiceConnection 實例:

private ServiceConnection connection = new ServiceConnection() {
 @Override
 public void onServiceConnected(ComponentName name, IBinder service) {
  Log.d(TAG, "onServiceConnected");
  FirstService.CustomBinder customBinder = (FirstService.CustomBinder) service;
  customBinder.init();
 }

 @Override
 public void onServiceDisconnected(ComponentName name) {
  Log.d(TAG, "onServiceDisconnected");
 }
};

現(xiàn)在,就可以通過 ServiceConnection 實例來綁定或者解綁服務啦。

綁定服務:

復制代碼 代碼如下:
bindService(new Intent(context, FirstService.class), connection, BIND_AUTO_CREATE);

bindService 接收三個參數(shù):

參數(shù)類型說明
serviceIntent這個 Intent 將綁定當前的活動類與服務類。
connServiceConnectionServiceConnection 對象。
flagsint綁定服務的方式。這里的 BIND_AUTO_CREATE 表示綁定后自動創(chuàng)建服務。

【綁定服務】輸出結(jié)果:

D/FirstService: onCreate D/MainActivity: onServiceConnected D/FirstService: init CustomBinder

解綁服務:

unbindService(connection);

只要傳入 ServiceConnection 對象即可解綁,是不是很簡單呀 O(∩_∩)O哈哈~

【解綁服務】輸出結(jié)果:

D/FirstService: onDestroy

以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持創(chuàng)新互聯(lián)。

網(wǎng)站名稱:說說在Android如何使用服務(Service)的方法
URL地址:http://muchs.cn/article16/ihsedg.html

成都網(wǎng)站建設公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站維護、移動網(wǎng)站建設、網(wǎng)站建設、營銷型網(wǎng)站建設、網(wǎng)站營銷、關鍵詞優(yōu)化

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)

網(wǎng)站建設網(wǎng)站維護公司