handling broadcast receiver
I have an app which has MainActivity(without gui.. please 开发者_运维技巧just flow with it:) )
now this MainActivity running a service, this service using sendBroadcast() in order to comunnicate with the MainActivity.. now ofcourse i need to registerReceiver in the onResume() of the MainActivity.
but i also need to add unregisterReceiver(receiver) in the onDestroy() of the MainActivity.
problem is: when i first start that app i need it to up the service, and i dont want the user to lose focus, so i press finish() after i`am starting the service.. but then auto invoked also unregisterReceiver(receiver).. and this is not good for me.. i get error it's said it couldnt find any registerd reciver.
so i fixed it by delete this line.. but i am sure its going to 'revenege' me in the future, when/where could i have problem if i wont use unregisterReceiver(receiver).. at the onDestroy()
mybe i should remove it (instead of delete it) to onPause()?
thanks,
ray.
Try calling bindService within onStart(), unbindService() within onStop(), registerReciever() within onResume() and unregisterReceiver() within onPause().
You might have a look at a piece of my working code. Maybe it can help you find your solution.
In the real project I commented the following:
bindService(new Intent(test1.this, MyService.class), mServiceConnection, Context.BIND_AUTO_CREATE);
unbindService(mServiceConnection);
and all of the mServiceConnection declaration.
I did it because it's actually a background service starting on system boot time. Otherwise they should not be commented.
@Override
public void onStart() {
super.onStart();
bindService(new Intent(test1.this, MyService.class), mServiceConnection, Context.BIND_AUTO_CREATE);
Intent serviceIntent = new Intent(this, MyService.class);
getApplicationContext().startService(serviceIntent);
Log.d(TAG, "onStart");
}
@Override
public void onStop() {
super.onStop();
unbindService(mServiceConnection);
}
@Override
public void onResume(){
super.onResume();
registerReceiver(receiver, new IntentFilter(MyService.BROADCAST_ACTION));
}
@Override
public void onPause() {
super.onPause();
unregisterReceiver(receiver);
}
private BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Log.d(TAG, "onRecieve");
constantCursor.requery(); // service finished its job, refresh ListView
}
};
private ServiceConnection mServiceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
mService = ((MyService.LocalBinder)service).getService();
Log.d(TAG, "onServiceConnected");
}
@Override
public void onServiceDisconnected(ComponentName name) {
// This is called when the connection with the service has been
// unexpectedly disconnected -- that is, its process crashed.
mService = null;
Log.d(TAG, "onServiceDisconnected");
}
};
精彩评论