如題,在Application 綁定了一個service 但是返回binder 並賦值這個操作特別慢
導致在 Activity 中通過Application 的方法獲取到的 binder 一直是空值。請問我該如何處理,才能獲取到 ?
public class MyApplication extends Application {
private MusicPlayService.PlayServiceBinder msbinder;
private ServiceConnection mConnection=new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
Log.d("綁定並開啟服務","綁定成功");
//獲取到bindler 了 可以並轉成service 可以調用裡面的方法了
msbinder= (MusicPlayService.PlayServiceBinder) service;
msbinder=getbinder();
Log.d("返回bindler",""+msbinder.toString());
}
@Override
public void onServiceDisconnected(ComponentName name) {
}
};
@Override
public void onCreate() {
super.onCreate();
Intent intent=new Intent(this,MusicPlayService.class);
startService(intent);
bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
}
//獲取綁定的Binder
public MusicPlayService.PlayServiceBinder getbinder(){
if(msbinder!=null){
Log.d("msbinder不為空","不為空");
}else {
Log.d("msbinder為空","空");
}
return msbinder;
}
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
application= (MyApplication) getApplication();
mSbinder=application.getbinder();
}
onServiceConnected連接完成之後回調,用binder的時候可能還沒連接服務完成,所以是空
兩種解決方法,回調和handler
1.定義回調接口
public interface TestListener {
public void onCompleted();
}
2.MyApplication
public class MyApplication extends Application {
private TestListener mListener = null;
@Override
public void onCreate() {
super.onCreate();
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
if(mListener!=null){
mListener.onCompleted(); // 這裡在你的onServiceConnected回調裡面調用
}
}
}, 1000);
}
public void setListener(TestListener l){
mListener = l;
}
}
3.Activity注冊回調
MyApplication app = (MyApplication) getApplication();
app.setListener(new TestListener(){
@Override
public void onCompleted() {
Log.d("", "test listener");// 綁定服務完成之後回調這裡
}
});
具體代碼不寫了,思路就是綁定服務不在Application裡面,寫一個Activity的基類BaseActivity,在這裡面綁定服務,定義一個handler,其他每個Activity都繼承這個基類,這樣每個activity都有一個handler實例,可以互相傳遞消息