我想发送值“从BroadcastReceiver到Activity”

时间:2017-06-22 05:56:15

标签: android android-activity broadcastreceiver

我想发送“从BroadcastReceiver到Activity”的值。 我不能得到“getIntExtra”。为什么呢?

MainActivity是“singleTask”。

  

源代码。

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?
    }
}

1 个答案:

答案 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;
    }
}