我想仅针对特定活动进行广播。如果活动被破坏,那么广播将不会触发。 我这样使用
protected void onStart() {
super.onStart();
LocalBroadcastManager.getInstance(this).registerReceiver((receiver),
new IntentFilter(GCMIntentService.COPA_RESULT)
);
}
receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
int count = intent.getIntExtra(GCMIntentService.COPA_MESSAGE, 0);
int youCount = intent.getIntExtra(GCMIntentService.COUNT_YOU, 0);
int reqCount = intent.getIntExtra(GCMIntentService.COUNT_REQ, 0);
if (count != 0) {
notificationcount.setVisibility(View.VISIBLE);
notificationcount.setText("" + count);
} else {
notificationcount.setVisibility(View.GONE);
}
AppCommon.notification_requestcount = reqCount;
AppCommon.notification_youcount = youCount;
AppCommon.notification_total_count = count;
}
};
我缺少的请提出这个
答案 0 :(得分:0)
如果你想这样做,只需做一件事就可以在Activity中注册Broadcast接收器,并在同一个Activity中取消注册。喜欢以下
@Override
protected void onStart() {
super.onStart();
LocalBroadcastManager.getInstance(this).registerReceiver((receiver),
new IntentFilter(GCMIntentService.COPA_RESULT)
);
}
@Override
protected void onStop() {
LocalBroadcastManager.getInstance(this).unregisterReceiver(receiver);
super.onStop();
}
receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
int count = intent.getIntExtra(GCMIntentService.COPA_MESSAGE, 0);
int youCount = intent.getIntExtra(GCMIntentService.COUNT_YOU, 0);
int reqCount = intent.getIntExtra(GCMIntentService.COUNT_REQ, 0);
if (count != 0) {
notificationcount.setVisibility(View.VISIBLE);
notificationcount.setText("" + count);
} else {
notificationcount.setVisibility(View.GONE);
}
AppCommon.notification_requestcount = reqCount;
AppCommon.notification_youcount = youCount;
AppCommon.notification_total_count = count;
}
};
答案 1 :(得分:0)
在Activity
内创建接收器并添加属性。同一时间,如果您希望在Activity
分别在register
和unregister
上onResume()
和onPause()
时销毁接收器。
演示:
在您的活动上创建BroadcastReceiver
:
private BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// your methods and actions for receiver
}
};
在您的活动onCreate()
方法中注册广播:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.your_layout);
your_activity_.this.registerReceiver(receiver, new IntentFilter(your_filter_action));
..
...
....
}
不要忘记在活动周期取消注册/注册:
@Override
protected void onResume() {
super.onResume();
your_activity.this.registerReceiver(receiver, new IntentFilter(your_filter_action));
}
@Override
protected void onPause() {
super.onPause();
your_activity.this.unregisterReceiver(receiver);
}
答案 2 :(得分:0)
您忘记取消注册广播接收器,请检查。
@Override
protected void onStop() {
LocalBroadcastManager.getInstance(this).unregisterReceiver(receiver);
super.onStop();
}