Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 學習筆記(五):Service 全面解析——從分類、生命週期到 Binder 跨進程通信

編輯:關於 Android 程式設計

一、Service 到底是什麼?

Service 是 Android 四大組件之一,官方文件對它的定義是:

A Service is an application component that can perform long-running operations in the background and does not provide a user interface...

用白話來說:Service 是一個沒有界面的應用組件,專門負責在後台默默幹活。其他組件可以把它拉起來,即使使用者切換到別的 App,它依然繼續運行;也可以綁定到它上面直接互動,甚至進行跨進程通信(IPC)。典型場景包括網絡請求、音樂播放、文件讀寫、與 ContentProvider 打交道等。

二、Service 的分類方式

2.1 按運行位置劃分

本地服務(LocalService):依附在主線程上,並不佔用獨立進程,因此更省內存,也不需要走 IPC 或 AIDL。缺點很直接——主進程被殺,服務跟著一起沒。播放音樂這類場景最常見。

遠程服務(RemoteService):跑在獨立進程裡,Activity 所在進程被殺也不影響它,可以同時服務多個進程。進程名的規則是「包名 + 你在 manifest 中指定的 android:process 字串」。這類服務通常會常駐內存、佔用一定資源,日常開發中比較少見,多為系統提供。

2.2 按運行方式劃分

前台服務:會在通知欄展示一個正在運行的圖標,服務被終止時圖標一併消失,對使用者有明確提示作用,例如音樂播放。

後台服務:不顯示通知圖標,默默運行,被終止時使用者毫無感知,例如天氣數據的定時更新。後台服務只要建立了通知並調用 startForeground(),就能升格為前台服務。

2.3 按啟動方式劃分

startService 啟動:主要用來丟一個後台任務,不涉及通信;停止用 stopService()。啟動後即使關聯的 Activity 銷毀,服務照樣運行。

bindService 啟動:為了通信而存在,停止用 unbindService()。一旦綁定的 Activity 銷毀,服務也會隨之銷毀。

兩者混用:既要 stopService() 又要 unbindService(),缺一不可。

三、Service 與 Thread 有什麼不同?

很多人會問:既然開個線程就能幹活,何必麻煩地用 Service?

Thread 是程序執行的最小單元、CPU 調度的基本單位,一個進程裡可以有很多線程,但線程無法脫離進程存在。它可以勝任各種異步操作。

Service 則是 Android 提供的一種機制。LocalService 的 onCreate()、onStartCommand() 等回調都跑在主進程上;RemoteService 則跑在獨立進程裡。

關鍵差別在於「歸屬」。線程是綁在 Activity 上的:Activity finish 之後,新啟動的 Activity 根本拿不到之前那個線程的引用,也就無法控制它。假設你需要一個線程每隔一段時間就連服務器同步數據,而這個線程必須在 Activity 不存在時也照樣運行——這時 Activity 一死,你就徹底失去了對它的掌控。

解法就是把線程放進 Service 裡:由 Service 創建、運行並管理它。任何 Activity 都能通過 startService()、stopService()、bindService()、unbindService() 來控制同一個 Service 實例,也可以在 Service 中註冊 BroadcastReceiver,從別處發廣播來指揮它。這些都是裸線程做不到的事。

四、Service 的生命週期

和 Activity 一樣,Service 也提供了一系列回調,讓我們感知狀態變化並在恰當時機做恰當的事。

從流程圖不難看出,使用 Service 有兩條路:純 startService()、純 bindService(),以及先啟動再綁定這種組合打法。

public class ExampleService extends Service {
    int mStartMode;       // 服務被殺後的行為策略
    IBinder mBinder;      // 供客戶端綁定使用的接口
    boolean mAllowRebind; // 是否允許 onRebind

    @Override
    public void onCreate() {
        // 服務首次創建,整個生命週期只走一次
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // 由 startService() 觸發,可被重複調用
        return mStartMode;
    }

    @Override
    public IBinder onBind(Intent intent) {
        // 由 bindService() 觸發,返回通信用的 IBinder
        return mBinder;
    }

    @Override
    public boolean onUnbind(Intent intent) {
        // 所有客戶端都解綁時回調
        return mAllowRebind;
    }

    @Override
    public void onRebind(Intent intent) {
        // onUnbind 之後又有新客戶端綁定
    }

    @Override
    public void onDestroy() {
        // 服務銷毀,只回調一次
    }
}

各回調的職責

onCreate():服務第一次被創建時立刻回調,整個生命週期中只執行一次。

onStartCommand(Intent, int, int):客戶端調用 startService() 時觸發。可以反覆調用,但不會新建實例,而是復用已有實例並再次回調此方法。

onBind(Intent):必須實現的方法,返回一個 IBinder 對象,App 靠它與 Service 通信。

onUnbind(Intent):該 Service 上所有綁定的客戶端都斷開時回調。

onRebind(Intent):在 onUnbind() 之後又有新客戶端嘗試綁定時調用。

onDestroy():服務被銷毀時回調,只執行一次。

startService 的行為

首次啟動會創建實例,依序走 onCreate()(只走一次)與 onStartCommand(),此時進入運行態。再次調用 startService() 不會新建對象,只會再回調一次 onStartCommand()。此後服務會一直在後台待着,不管對應 Activity 是否還活着,直到有人調用 stopService() 或服務自己調用 stopSelf()。當然,系統資源緊張時 Android 也可能主動結束它。

bindService 的行為

某個 Activity 通過 bindService() 綁定後,後續再綁定不會新建實例,也不會再調用 onBind(),而是直接把已有的 IBinder 交給新來的客戶端。無論綁定多少次,onCreate() 只走一次,onStartCommand() 則永遠不會被調用。連接建立後服務持續運行,直到調用 unbindService(),或者發起綁定的 Context 不復存在(例如 Activity finish),系統會自動停止服務並觸發 onDestroy()。

先 startService 再 bindService

這種混合模式下服務會一直在後台待着。onCreate() 無論如何只走一次,而 startService() 調用幾次,onStartCommand() 就走幾次。此時光調 unbindService() 是停不掉服務的,必須再調 stopService() 或 stopSelf()。

幾個容易踩的坑

用 bindService() 就必須在某處配對 unbindService();用 startService() 就必須配對 stopService();兩者同時使用時,必須 unbindService() 與 stopService() 都調到,服務才會真正停止,且與調用先後無關——先解綁則要等 stopService 才停,先 stop 則要等解綁或原 Context 銷毀才停。

此外:屏幕旋轉時,默認情況下 bindService 會斷開;Service 必須在 AndroidManifest.xml 中註冊才能使用。

五、IntentService:偷懶者的福音

Service 和 Activity 一樣跑在主線程上,直接在裡面做耗時操作會 ANR。於是 Google 提供了 IntentService。

簡單說,IntentService 是繼承自 Service、專門處理異步請求的類。內部有一條工作線程替你幹活,啟動方式和普通 Service 一模一樣,而且任務跑完會自動停止,不用你手動管理。你可以連續啟動它多次,每個耗時任務會以 worker queue 的方式在 onHandleIntent() 裡排隊執行,同一時間只有一個 worker 線程在工作,第一個做完才轮到第二個。所有請求都在單線程裡串行處理,既不阻塞 UI 線程,也不需要你自己寫同步。

實現上它走的是 Handler 思路:內部建了一個叫 ServiceHandler 的 Handler,直接綁到 HandlerThread 對應的子線程上,並把「處理一個 Intent」這件事封裝進 onHandleIntent() 這個抽象方法。你只要實現它,按 Intent 的不同分支處理即可。另外它默認實現的 onBind() 返回 null。

使用只需兩步:寫一個無參構造函數並在其中調用 super("name");然後實現 onHandleIntent()。構造函數必須是無參的,因為 Service 的實例化由系統完成,系統用的就是無參構造。

public class MyIntentService extends IntentService {
    private static final String TAG = "robin";

    public MyIntentService() {
        super("com.lenovo.robin.test.MyIntentService");
        Log.i(TAG, this + " is constructed");
    }

    @Override
    protected void onHandleIntent(Intent arg0) {
        Log.i(TAG, "begin onHandleIntent() in " + this);
        try {
            Thread.sleep(10 * 1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        Log.i(TAG, "end onHandleIntent() in " + this);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.i(TAG, this + " is destroy");
    }
}

翻開源碼,它的骨架其實非常精簡:

public abstract class IntentService extends Service {
    private volatile Looper mServiceLooper;
    private volatile ServiceHandler mServiceHandler;
    private String mName;
    private boolean mRedelivery;

    private final class ServiceHandler extends Handler {
        public ServiceHandler(Looper looper) {
            super(looper);
        }
        @Override
        public void handleMessage(Message msg) {
            onHandleIntent((Intent) msg.obj);
            stopSelf(msg.arg1);
        }
    }

    public IntentService(String name) {
        super();
        mName = name;
    }

    public void setIntentRedelivery(boolean enabled) {
        mRedelivery = enabled;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        HandlerThread thread = new HandlerThread("IntentService[" + mName + "]");
        thread.start();
        mServiceLooper = thread.getLooper();
        mServiceHandler = new ServiceHandler(mServiceLooper);
    }

    @Override
    public void onStart(Intent intent, int startId) {
        Message msg = mServiceHandler.obtainMessage();
        msg.arg1 = startId;
        msg.obj = intent;
        mServiceHandler.sendMessage(msg);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        onStart(intent, startId);
        return mRedelivery ? START_REDELIVER_INTENT : START_NOT_STICKY;
    }

    @Override
    public void onDestroy() {
        mServiceLooper.quit();
    }

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

    protected abstract void onHandleIntent(Intent intent);
}

六、動手實戰

6.1 用 startService 啟動

自定義類繼承 Service:

public class FirstService extends Service {
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}

在清單文件中註冊:

<service android:name=".Service.FirstService" />

在 Activity 中拉起來:

btn_start_service = (Button) findViewById(R.id.btn_start_service);
btn_start_service.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        Intent intent = new Intent(getApplicationContext(), FirstService.class);
        startService(intent);
    }
});

這樣就完成了一個最小可用的 Service。由於它不會隨 Activity 銷毀而銷毀,記得在合適的地方調用 stopService() 收尾。

6.2 與 Activity 綁定的 Service

public class SecondService extends Service {
    private final String TAG = "SecondService";
    private int count;
    private boolean quit;
    private MyBinder binder = new MyBinder();

    public class MyBinder extends Binder {
        public int getCount() {
            return count;
        }
    }

    @Override
    public IBinder onBind(Intent intent) {
        System.out.println("onBind 被調用");
        return binder;
    }

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public boolean onUnbind(Intent intent) {
        System.out.println("onUnbind 被調用");
        return true;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        this.quit = true;
        System.out.println("onDestroy 被調用");
    }

    @Override
    public void onRebind(Intent intent) {
        System.out.println("onRebind 被調用");
        super.onRebind(intent);
    }
}

MainActivity 中的綁定邏輯:

btn_bind_service = (Button) findViewById(R.id.btn_bind_service);
btn_bind_service.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        Intent intent = new Intent(getApplicationContext(), SecondService.class);
        getApplicationContext().bindService(intent, mServiceConnection, Service.BIND_AUTO_CREATE);
    }
});

ServiceConnection mServiceConnection = new ServiceConnection() {
    @Override
    public void onServiceConnected(ComponentName name, IBinder service) {
        System.out.println("------->> service connected");
    }

    @Override
    public void onServiceDisconnected(ComponentName name) {
        System.out.println("--------------->> service disconnected");
    }
};

6.3 IntentService 實例

public class ThridService extends IntentService {
    public ThridService() {
        super("");
        System.out.println("intent service constructed");
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        String flag = intent.getExtras().getString("flag");
        if ("t1".equals(flag)) {
            System.out.println("startServiceT1");
        } else if ("t2".equals(flag)) {
            System.out.println("startServiceT2");
        }
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

接連丟兩個任務進去,可以觀察到它們嚴格串行執行:

btn_intent_service = (Button) findViewById(R.id.btn_intent_service);
btn_intent_service.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        Intent it1 = new Intent(getApplicationContext(), ThridService.class);
        Bundle b1 = new Bundle();
        b1.putString("flag", "t1");
        it1.putExtras(b1);

        Intent it2 = new Intent(getApplicationContext(), ThridService.class);
        Bundle b2 = new Bundle();
        b2.putString("flag", "t2");
        it2.putExtras(b2);

        getApplicationContext().startService(it1);
        getApplicationContext().startService(it2);
    }
});

這裡只演示了最基礎的啟動方式,更複雜的場景沒有展開。

七、Binder 機制與 AIDL

7.1 為什麼 Android 要用 Binder

Android 內核源自 Linux,卻沒有採用 Linux 原生那套 IPC 機制,而是自造了 Binder。每個應用跑在獨立進程裡以保證互不干擾,但 Activity 常常需要和系統 Service 通信,兩者顯然不在同一進程——Binder 就是官方給出的答案之一。

Binder 體系由 Client、Server、ServiceManager 與 Binder 驅動四部分組成:前三者跑在用戶空間,驅動跑在內核空間。

Client 端:想訪問遠程服務,必須先拿到對應 Binder 在驅動層的 mRemote 引用,之後就能通過它調用遠程方法。

Server 端:本質上就是一個 Binder 類對象。創建時內部會開一條線程,專門接收驅動轉發的消息並執行相應的服務代碼。

ServiceManager:一個守護進程,負責管理各個 Server,並向 Client 提供查詢 Server 接口的能力。

Binder 驅動:Server 成功創建 Binder 對象後,驅動會相應生成一個 mRemote 對象(同為 Binder 類型),Client 正是靠它訪問遠程服務。

7.2 用 AIDL 實現兩進程通信

先在 main 目錄下新建 aidl 文件夾,在其中建立與 aidl 包名一致的包,然後新建 aidl 文件:

// IPerson.aidl
package com.example.devin.helloservice.aidl;

interface IPerson {
    String findPersion(int num);
}

編譯後可以在 build/generated/source/aidl 下找到自動生成的 Java 代碼,核心要點是 Stub 抽象類與 Proxy 代理類:

public interface IPerson extends android.os.IInterface {

    public static abstract class Stub extends android.os.Binder implements IPerson {
        private static final java.lang.String DESCRIPTOR = "com.example.devin.helloservice.aidl.IPerson";

        public Stub() {
            this.attachInterface(this, DESCRIPTOR);
        }

        public static IPerson asInterface(android.os.IBinder obj) {
            if ((obj == null)) {
                return null;
            }
            android.os.IInterface iin = obj.queryLocalInterface(DESCRIPTOR);
            if (((iin != null) && (iin instanceof IPerson))) {
                return ((IPerson) iin);
            }
            return new IPerson.Stub.Proxy(obj);
        }

        @Override
        public android.os.IBinder asBinder() {
            return this;
        }

        @Override
        public boolean onTransact(int code, android.os.Parcel data, android.os.Parcel reply, int flags)
                throws android.os.RemoteException {
            switch (code) {
                case INTERFACE_TRANSACTION: {
                    reply.writeString(DESCRIPTOR);
                    return true;
                }
                case TRANSACTION_findPersion: {
                    data.enforceInterface(DESCRIPTOR);
                    int _arg0;
                    _arg0 = data.readInt();
                    java.lang.String _result = this.findPersion(_arg0);
                    reply.writeNoException();
                    reply.writeString(_result);
                    return true;
                }
            }
            return super.onTransact(code, data, reply, flags);
        }

        private static class Proxy implements IPerson {
            private android.os.IBinder mRemote;

            Proxy(android.os.IBinder remote) {
                mRemote = remote;
            }

            @Override
            public android.os.IBinder asBinder() {
                return mRemote;
            }

            public java.lang.String getInterfaceDescriptor() {
                return DESCRIPTOR;
            }

            @Override
            public java.lang.String findPersion(int num) throws android.os.RemoteException {
                android.os.Parcel _data = android.os.Parcel.obtain();
                android.os.Parcel _reply = android.os.Parcel.obtain();
                java.lang.String _result;
                try {
                    _data.writeInterfaceToken(DESCRIPTOR);
                    _data.writeInt(num);
                    mRemote.transact(Stub.TRANSACTION_findPersion, _data, _reply, 0);
                    _reply.readException();
                    _result = _reply.readString();
                } finally {
                    _reply.recycle();
                    _data.recycle();
                }
                return _result;
            }
        }

        static final int TRANSACTION_findPersion = (android.os.IBinder.FIRST_CALL_TRANSACTION + 0);
    }

    public java.lang.String findPersion(int num) throws android.os.RemoteException;
}

接著自定義 Service 並繼承 IPerson.Stub——這一步同時實現了 IPerson 與 IBinder 兩個接口:

public class AIDLService extends Service {
    private String[] names = {"張三", "李四", "王五", "趙六", "孫七"};
    private IBinder mIBinder = new PersionBinder();

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return mIBinder;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        System.out.println("start service");
        return super.onStartCommand(intent, flags, startId);
    }

    private class PersionBinder extends IPerson.Stub {
        @Override
        public String findPersion(int num) throws RemoteException {
            if (num > 0 && num < 6) {
                return names[num - 1];
            }
            return "沒有這個人";
        }
    }
}

客戶端通過 asInterface() 把 IBinder 轉成本地接口,之後就能像調本地方法一樣使用:

public class SecondActivity extends AppCompatActivity implements View.OnClickListener {
    EditText et_num;
    Button btn_find;
    TextView tv_name;
    IPerson mIPerson;
    PersionConnect mPersionConnect = new PersionConnect();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_aidl);
        et_num = (EditText) findViewById(R.id.et_num);
        btn_find = (Button) findViewById(R.id.btn_find);
        tv_name = (TextView) findViewById(R.id.tv_name);

        Intent intent = new Intent(this, AIDLService.class);
        startService(intent);
        this.bindService(intent, mPersionConnect, Service.BIND_AUTO_CREATE);
        btn_find.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        String etNum = et_num.getText().toString().trim();
        int num = Integer.valueOf(etNum);
        try {
            tv_name.setText(mIPerson.findPersion(num));
        } catch (RemoteException e) {
            e.printStackTrace();
        }
        et_num.setText("");
    }

    private class PersionConnect implements ServiceConnection {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            mIPerson = IPerson.Stub.asInterface(service);
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            mIPerson = null;
        }
    }
}

至此,一次簡單的跨進程調用就跑通了。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved