我有 1活动和 1服务。当活动进入后台时,将启动服务,当活动进入前台时,服务将停止。当服务停止时,我想通过意图将对象从它发送到活动。这是我的代码
MyActivity.java
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(ACTION_WITH_RLM)) {
//I will get the object received by service here
}
}
};
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_record_lesson_ins);
localBroadcastManager = LocalBroadcastManager.getInstance(this);
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(ACTION_WITH_RLM);
localBroadcastManager.registerReceiver(broadcastReceiver, intentFilter);
}
@Override
protected void onResume() {
super.onResume();
if (intent != null) {
stopService(intent);
}
}
@Override
protected void onPause() {
super.onPause();
if (intent != null) {
startService(intent);
}
}
@Override
protected void onStop() {
super.onStop();
localBroadcastManager.unregisterReceiver(broadcastReceiver);
}
MyService.java
private RecordLessonModel recordLessonModel;
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
//I code sth for handle recordLessonModel object
return START_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
Intent intent = new Intent(MyActivity.ACTION_WITH_RLM);
intent.putExtra(MyActivity.RECORD_MODEL_NAME, Parcels.wrap(recordLessonModel));
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}
此处的问题是我的broadcastReceiver
MyActivity
在活动到达前台时无法接收服务意图。我不知道为什么。
感谢。
答案 0 :(得分:1)
您应该考虑将您的broadcastReceiver取消注册到onDestory()
而不是onStop()
因为你的brodcastReceiver在活动变为背景时未注册。
有关HERE
的更多信息,请参阅