BindService標準寫法

BindService標準寫法

在使用bindservice時,經常會忽略掉死亡回調的作用,下面提供一個標準的bindService的使用流程,僅供參考


import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;
import ITestBinder;

public class Test extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Intent intent = new Intent("xxxx");
        bindService(intent,serviceConnection, Context.BIND_AUTO_CREATE); //綁定service
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbindService(serviceConnection); //解綁service
    }

    ITestBinder iBinder;
    ServiceConnection serviceConnection = new ServiceConnection() {
    
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            iBinder = ITestBinder.Stub.asInterface(service);
            try {
                // 註冊死亡回調
                iBinder.asBinder().linkToDeath(mDeathRecipient, 0);
                //TODO 想要進行的主業務
            } catch (RemoteException e) {
                Log.e("TAG", "onServiceConnected:" + e.getMessage());
            }


        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

            iBinder = null; //資源釋放
        }
    };


    /**
     * 死亡回調 service異常結束時 客戶端會在這個回調函數裏得到通知
     */
    IBinder.DeathRecipient mDeathRecipient = new IBinder.DeathRecipient() {
        @Override
        public void binderDied() {

            iBinder.asBinder().unlinkToDeath(mDeathRecipient, 0); //釋放死亡回調
            iBinder = null; //資源釋放
            //TODO 其他處理,例如重新綁定service等

        }
    };
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章