我想发送“从BroadcastReceiver到Activity”的值。 我不能得到“getIntExtra”。为什么呢?
源代码。
public class TimerReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
intent.setClass(context,MainActivity.class);
intent.putExtra("ALARM_FLAG", 7);
// -> set 7.
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
try {
pendingIntent.send();
} catch (PendingIntent.CanceledException e) {
e.printStackTrace();
}
}
}
public class MainActivity extends AppCompatActivity {
@Override
protected void onResume(){
super.onResume();
Intent intent = getIntent();
int a = intent.getIntExtra("ALARM_FLAG", 0);
// -> This "a" is 0. why?
}
}
答案 0 :(得分:0)
首先,您需要在活动上注册接收者,
private BroadcastReceiver updateReceiver;
private void registerUpdateReciever() {
IntentFilter filter = new IntentFilter();
filter.addAction("An unique string constant"); // eg: "broad_cast_filter_update_receiver"
if (updateReceiver == null) {
updateReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction()
.equalsIgnoreCase("An unique string constant")) { // "broad_cast_filter_update_receiver"
// get values from intent
}
}
};
registerReceiver(updateReceiver, filter);
}
}
在广播接收器中
try {
Intent intent = new Intent();
// intent put desired values
intent.setAction("An unique string constant"); // "broad_cast_filter_update_receiver"
sendBroadcast(intent);
} catch (Exception e) {
e.printStackTrace();
}
并在onStop()
回调或onDestroy()
回调活动
@Override
protected void onStop() {
super.onStop();
if (updateReceiver != null) {
unregisterReceiver(updateReceiver);
updateReceiver = null;
}
}