我有一个Android服务,我需要停止并重新启动。在服务的onDestroy()
中,我有一些清理代码可能需要一段时间才能执行。
是否有通知使用该服务的应用程序已完成执行onDestroy()
?或者应用程序可以做些什么来检查onDestroy()
是否已完成执行?
答案 0 :(得分:2)
是的,在onDestroy()方法中使用broadcast!
Intent intent = new Intent( "Service_destroyed" );
// You can also include some extra data.
intent.putExtra("message", "Service is destroyed!");
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
这将通知其他活动。请务必先在活动中注册广播,并在不再需要时注销。
寄存器:
LocalBroadcastManager.getInstance(this).registerReceiver(mServiceDestroyedReceiver, new IntentFilter( "Service_destroyed" ));
以下是捕捉广播的方法:
private BroadcastReceiver mServiceDestroyedReceiver= new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// Get extra data included in the Intent
String message = intent.getStringExtra("message");
Log.d(TAG, "Service is destroyed message: " + message);
}
};
取消注册广播接收器:
LocalBroadcastManager.getInstance(this).unregisterReceiver( mServiceDestroyedReceiver);