天天看點

Android多程序之Binder的意外死亡及權限校驗

Android多程序系列

通過前幾篇文章,我們對Binder的使用和工作流程有了一定的了解,但是還有幾個問題休要我們去解決。一個是如果服務端程序意外退出,Binder死亡,那用戶端就會請求失敗;還有一個就是權限校驗問題,就是服務端需要校驗一下用戶端的身份權限,不能誰都能請求服務端的服務

Binder意外死亡的處理

給Binder設定DeathRecipient監聽
  • 在綁定Service服務後的onServiceConnected回調中給Binder注冊死亡回調DeathRecipient
private ServiceConnection mConnection = new ServiceConnection() {
    @Override
    public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
        Log.e(TAG, "ServiceConnection-->"+ System.currentTimeMillis());
        IBookManager bookManager = BookManagerImpl.asInterface(iBinder);
        mRemoteBookManager = bookManager;
        try {
            //注冊死亡回調
            iBinder.linkToDeath(mDeathRecipient,0);
            ...

        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onServiceDisconnected(ComponentName componentName) {
        Log.e(TAG, "onServiceDisconnected-->binder died");
    }
};           
  • 在DeathRecipient中相應的處理,比如重新連接配接服務端
private IBinder.DeathRecipient mDeathRecipient = new IBinder.DeathRecipient() {
    @Override
    public void binderDied() {
        Log.e(TAG, "mDeathRecipient-->binderDied-->");
        if (mRemoteBookManager == null) {
            return;
        }
        mRemoteBookManager.asBinder().unlinkToDeath(mDeathRecipient, 0);
        mRemoteBookManager = null;
        //Binder死亡,重新綁定服務
        Log.e(TAG, "mDeathRecipient-->bindService");
        Intent intent = new Intent(MainActivity.this, BookManagerService.class);
        bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
    }
};           
  • 為了測試,我們在服務端添加結束程序的代碼
@Override
public void onCreate() {
    super.onCreate();
    Log.e(TAG, "onCreate-->"+ System.currentTimeMillis());
    new Thread(new ServiceWorker()).start();
}

private class ServiceWorker implements Runnable {
    @Override
    public void run() {
        while (!mIsServiceDestoryed.get()) {
            try {
                Thread.sleep(5000);
            }catch (InterruptedException e) {
                e.printStackTrace();
            }

            int bookId = mBookList.size() + 1;
            if (bookId == 8) {
                //結束目前程序,測試Binder死亡回調
                android.os.Process.killProcess(android.os.Process.myPid());
                return;
            }
            ...
        }
    }
}           
  • 測試效果
從上面的測試我們可以看到用戶端在服務端程序意外退出後,通過重新綁定服務又把服務端程序啟動了。此外,我們還可以在ServiceConnection的onServiceDisconnected方法中處理服務端程序意外退出的情況,方法是一樣的,就不測試了。2種方法的差別就在于onServiceDisconnected方法在用戶端的UI線程中被回調,而binderDied方法在用戶端的Binder線程池中被回調

權限驗證

在onBind中通過自定義權限來驗證
  • 首先要自定義一個權限
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.xxq2dream.android_ipc">
    
    <permission
        android:name="com.xxq2dream.permission.ACCESS_BOOK_SERVICE"
        android:protectionLevel="normal"/>
    
</manifest>           
  • 然後在Service中的onBind方法中校驗
@Nullable
@Override
public IBinder onBind(Intent intent) {
    Log.e(TAG, "onBind-->"+ System.currentTimeMillis());
    int check = checkCallingOrSelfPermission("com.xxq2dream.permission.ACCESS_BOOK_SERVICE");
    if (check == PackageManager.PERMISSION_DENIED) {
        Log.e(TAG, "PERMISSION_DENIED");
        return null;
    }
    Log.e(TAG, "PERMISSION_GRANTED");
    return mBinder;
}           
  • 從上圖中我們可以看到,由于我們的應用用戶端沒有聲明服務端校驗的權限,是以服務端校驗不通過,我們隻需要在我們的用戶端添加相應的權限聲明即可
<uses-permission android:name="com.xxq2dream.permission.ACCESS_BOOK_SERVICE"/>
           
在onTransact方法中進行權限校驗
private Binder mBinder = new BookManagerImpl(){
    @Override
    public List<Book> getBookList() throws RemoteException {
        Log.e(TAG, "getBookList-->"+ System.currentTimeMillis());
        return mBookList;
    }

    ...
    
    @Override
    public boolean onTransact(int code, Parcel data, Parcel reply, int flags) throws RemoteException {
        int check = checkCallingOrSelfPermission("com.xxq2dream.permission.ACCESS_BOOK_SERVICE");
        if (check == PackageManager.PERMISSION_DENIED) {
            Log.e(TAG, "PERMISSION_DENIED");
            return false;
        }
        
        String packageName = null;
        //擷取用戶端包名 
        String[] packages = getPackageManager().getPackagesForUid(getCallingUid());
        if (packages != null && packages.length > 0) {
            packageName = packages[0];
        }
        //校驗包名
        if (!packageName.startsWith("com.xxq2dream")) {
            return false;
        }
        Log.e(TAG, "PERMISSION_GRANTED");
        return super.onTransact(code, data, reply,flags);
    }
};           
結語
  • Binder的一個很好的應用就是推送消息和保活。比如我們可以建立一個Service運作在一個獨立的程序中,然後和我們的應用程序中的一個Service綁定。獨立程序的Service每隔一定的時間向我們的服務端請求檢視是否有新的消息,有的話就拉取新的消息,然後通知給應用程序的Service,執行彈出通知之類的操作。應用程式退出後,我們的Service程序還是存活的,這樣就可以一直接收消息。當然,如果使用者一鍵清理或是直接結束應用的話,我們的Service程序仍然會被幹掉。

歡迎關注我的微信公衆号,期待與你一起學習,一起交流,一起成長!

繼續閱讀