我卡在一個服務綁定,給我堅果的問題。Android - 我的服務onunbind,但沒有再綁定
我得到了一項綁定服務的活動,並且用戶頻繁地進出該活動。
問題出現在用戶第一次出去活動時這個unBinds服務和什麼時候再進去,不再綁定。
活動調用綁定服務是這樣的:
@Override
protected void onStart() {
super.onStart();
Intent intent = new Intent(this, CService.class);
intent.putExtra("id_local", (String) getIntent().getExtras().get("id_local"));
intent.putExtra("id_send", (String) getIntent().getExtras().get("id_send"));
bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
registerReceiver(uiUpdated, new IntentFilter("SERVER_MESAGE"));
mBound = true;
}
凡mConnection
定義這樣:
private ServiceConnection mConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName className,
IBinder service) {
CService.LocalBinder binder =(CService.LocalBinder) service;
mService = binder.getService();
Log.d("Service", "onServiceConnected");
mBound = true;
}
@Override
public void onServiceDisconnected(ComponentName arg0) {
Log.d("Service", "onServiceDisconnected");
mBound = false;
}
};
而在onStop
我unbindService
:
@Override
protected void onStop() {
if (mBound) {
Log.d("ActivityStop", "Stoping activity");
unregisterReceiver(uiUpdated);
unbindService(mConnection);
mBound = false;
}
super.onStop();
}
的onBind
在服務e是一個:
@Override
public IBinder onBind(Intent intent) {
final String id_local = intent.getStringExtra("id_local");
final String id_send = intent.getStringExtra("id_send");
if (!misatgesList.isEmpty()) {
misatgesList.clear();
}
mBackGroundTimer.schedule(new TimerTask() {
@Override
public void run() {
String serverResult = restRecive(id_local, id_send,
misatgesList.size());
if (serverResult != null) {
misatgesList.addAll(procesMisatges(serverResult,
id_local));
Intent i = new Intent("SERVER_MESAGE");
i.putExtra("recive", serverResult);
sendBroadcast(i);
}
}
}, 0, 1000);
return mBinder;
}
而且onUnBind
是一個:
@Override
public boolean onUnbind(Intent intent) {
mBackGroundTimer.cancel();
misatgesList.clear();
Log.d("ServiceOnUnBind", "ServiceOnUnBind");
//stopSelf();
return super.onUnbind(intent);
}
所以我的問題是,如何在活動中再次變爲我能再次綁定的服務?或者我應該怎麼做才能保持綁定活動直到用戶進入活動?
從如下活動綁定到您的服務時
感謝答案,我試圖'getApplicationContext()'添加到代碼(在'在onStart()'的活動,並在'onStop()'因爲有我做'unbindService()')並且仍然不工作... – ALanao