放弃并获得广播接收器

时间:2015-10-01 10:07:06

标签: java android broadcastreceiver

如何获取我放入广播接收器的值? 请帮帮我

在我的活动中

public static void startActivity(Context context) {
   //what can i put here?
}

在意图服务中

intent.putExtra("DriversID", 1351351);
sendBroadcast(intent);

我的广播发布者

public class GcmBroadcastReceiver extends WakefulBroadcastReceiver {

   @Override
    public void onReceive(Context context, Intent intent) {

     Bundle bundle = intent.getExtras();

    String DriversID = null;
    if (bundle != null) {
        DriversID = bundle.getString("DriversID");
        Toast.makeText(context, "DriversID", Toast.LENGTH_LONG).show();
    }

    Intent i = new Intent(context, DashboardActivity.class);
    i.putExtra("getDriversID", DriversID);
    context.startActivity(i);


    ComponentName comp = new ComponentName(context.getPackageName(),
            GcmIntentService.class.getName());
    startWakefulService(context, (intent.setComponent(comp)));
    setResultCode(Activity.RESULT_OK);
     }
}

这是确切的情况,当GCM通知我时我将从意图中获取消息并将其发布到广播,然后活动将获得消息的值,那该怎么样?

2 个答案:

答案 0 :(得分:0)

您可以在活动中创建一个BroadcastReciever:

    private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {

        // Extract data included in the Intent
        // String message = intent.getStringExtra("message");
        // do other stuff here
    }
};

然后你应该在你的活动中注册(例如在onResume中):

this.registerReceiver(mMessageReceiver, new IntentFilter("unique_name"));

请记住取消注册(在onPause,选择适合您需求的任何内容):

protected void onPause() {
        super.onPause();
        this.unregisterReceiver(mMessageReceiver);
}

要发送数据,您可以使用:

Intent intent = new Intent("unique_name");

    // put whatever data you want to send, if any
    // intent.putExtra("message", "some data");

    // send broadcast
    context.sendBroadcast(intent);
}

答案 1 :(得分:0)

这样做。     设置意图动作并发送广播。

intent.setAction(action);

并检查接收器中的动作以找到意图

 public void onReceive(Context context, Intent intent) {
    if(intent.getAction().equals(action))
    String DriversID = intent.getStringExtra("DriversID");
    }