天天看點

Android 四大元件之一(Service詳解)

做個Service的筆記,有不足錯誤的地方望指出,謝謝。

一、什麼是Service?

Service,又稱背景服務,是Android四大元件之一,一種程式背景運作的解決方案,用于不需與使用者互動長期在背景運作的操作,或者給其他應用程式提供使用的功能。

兩個特點:

  • 不依賴于使用者可視的UI界面(不是絕對的)
  • 具有長時間運作的特點
二、建立一個服務方式:

方法1、包名上點選右鍵 New – Service – Service 完成建立,并在AndroidManifest.xml自動完成注冊。

Android 四大元件之一(Service詳解)

方法2、包名上點選右鍵 New – Class 建立腳本,繼承 extends Service,手動在AndroidManifest.xml完成注冊。

Android 四大元件之一(Service詳解)

3、建立代碼:

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;

public class MyService extends Service {
    public MyService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }
}
           
//在AndroidManifest.xml中注冊
<service
    android:name=".MyService"
    android:enabled="true"
    android:exported="true">
</service>
           
三、*啟動方式 *:

1、startService() 方式:

//啟動服務
Intent intent = new Intent(this, MyService.class);
startService(intent);
           
//停止服務
Intent intent = new Intent(this, TestOneService.class);
stopService(intent);
           

(1) 特點:

一旦服務開啟就跟開啟者沒關系了,開啟者退出或者挂了,服務還會在背景長期運作,開啟者不能調用服務裡面的方法。

(2) 生命周期:

  • onCreate():隻會在第一次建立Service時執行一次,是和完成一些初始化。
  • onStartCommand():每調用一次 startService() 就會執行一次onStartCommand()方法。此方法很重要,在該方法中會根據傳入的Intent參數進行實際操作,比如在此處建立一個線程用于下載下傳資料或播放音樂等。
  • onBind():抽象方法,必須重寫的,及時用不到。
  • onDestory():銷毀時會執行該方法。

2、bindService() 方式:

通過bindService綁定的服務,是典型的C/S模式。調用者是client端,service則是server端。

下面是使用的簡單概述:

Service 服務端:

簡述:定義一個繼承 extends Service 的BindServiceTest,再在BindServiceTest中定義一個繼承extends Binder 的MyBinder來擷取Service執行個體,用來實作C/S之間的通信,以下為相關代碼:

public class BindServiceTest extends Service {
    //C - 可以通過Binder擷取Service執行個體
    public class MyBinder extends Binder {
        public BindServiceTest getService() {
            return BindServiceTest.this;
        }
    }
    //通過binder實作調用者C/S之間的通信
    private MyBinder binder = new MyBinder();
    @Override
    public void onCreate() {
        super.onCreate();
    }
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return START_NOT_STICKY;
    }
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return binder;
    }
    @Override
    public boolean onUnbind(Intent intent) {
        return false;
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    private final Random random = new Random();
    //公共方法 - 供C随意調用
    public int getRandomTest() {
        return random.nextInt();
    }
}
           

注冊Service:

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

Client 調用者(ActivityA):

簡述:

定義一個ServiceConnection參數,在此參數中可以通過在BindServiceTest服務中定義的binder來擷取執行個體,之後可以通過binder調用寫好的公共方法了。

private BindServiceTest service = null;
    private boolean isBind = false;
    private ServiceConnection conn = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder binder) {
            isBind = true;
            //擷取執行個體
            BindServiceTest.MyBinder myBinder = (BindServiceTest.MyBinder) binder;
            service = myBinder.getService();
            int num = service.getRandomTest();
        }
        @Override
        public void onServiceDisconnected(ComponentName name) {
            isBind = false;
        }
    };
           

綁定Service:

private void btnBindService(){
        Intent intent = new Intent(ActivityA.this, BindServiceTest.class);
        intent.putExtra("from", "ActivityA");
        bindService(intent, conn, BIND_AUTO_CREATE);
    }
           

解綁Service:

private void btnUnbindService(){
        if (isBind) {
            unbindService(conn);
        }
    }
           

(2) 特點:

  • bindService開啟的Service一旦開啟,與調用者綁定,調用者挂了,Service也會跟着挂了,當沒有任何調用者與Service綁定時,Service會自行銷毀。
  • 調用者可以調用Service裡面的方法。

(3) 生命周期:

  • onCreate():在未綁定情況下調用bindService執行一次,已經綁定的情況下調用bindService不執行。
  • onBind():在未綁定情況下調用bindService執行一次,已經綁定的情況下調用bindService不執行。
  • onUnbind():再綁定之後調用此方法,解除綁定Service。
  • onDestory():解除綁定時會執行該方法。