【问题标题】:Pass data from Activity to Broadcast Receiver with Intent将数据从 Activity 传递到带有 Intent 的广播接收器
【发布时间】:2020-05-15 10:04:46
【问题描述】:

我正在通过BroacastReciever 在特定时间安排通知。我想将数据从通知点击传递到活动的newIntent 方法。到目前为止,通知通过后一切正常。但是,我在将数据从 activity 传递到我的 BrocastReceiver 类时遇到问题。 问题是我传递的变量存在于我的activity 类中,而不是broadcastReceiver。我不知道如何将这些数据放入我的接收器类中。

Activity.java

private void setTimer(String place){
        AlarmManager alarmManager = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
        Intent intent = new Intent(this, BroadcastAlarm.class);
        intent.setAction("MY_NOTIFICATION_MESSAGE");
        intent.putExtra("place", place); //this doesn't send data to notification. I want to send place string to notification
        PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 100, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
    }

BroadcastReceiver.java

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

  Intent intent1 = new Intent(context, SearchActivity.class);
intent1.putExtra("place", stringNotHere); //if I send data from here it gets available but the problem is that my place data is on my activity class not here
   intent1.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(context, 100, intent1, PendingIntent.FLAG_UPDATE_CURRENT);
        NotificationCompat.Builder notification= new NotificationCompat.Builder(context, NOTIFICATION_CHANNEL_ID);
        notification.setContentIntent(pendingIntent)
    }

如您所见,我需要使我的活动的place 变量在BroadcastReceiver 上可用。我该怎么做?

【问题讨论】:

    标签: java android broadcastreceiver android-notifications


    【解决方案1】:

    替换:

    intent1.putExtra("place", stringNotHere);
    

    有了这个:

    String place = intent.getStringExtra("place");
    intent1.putExtra("place", place);
    

    【讨论】:

      猜你喜欢
      • 2012-10-10
      • 1970-01-01
      • 1970-01-01
      • 2021-03-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多