简体   繁体   English

将数据从 Activity 传递到带有 Intent 的广播接收器

[英]Pass data from Activity to Broadcast Receiver with Intent

I am scheduling a notification at a particular time via BroacastReciever .我正在通过BroacastReciever在特定时间安排通知。 I want to pass data from notification click to activity's newIntent method.我想将数据从通知点击传递到活动的newIntent方法。 So far everything works well as the notifications come through.到目前为止,通知通过后一切正常。 However, I have an issue passing data from activity to my BrocastReceiver class.但是,我在将数据从activity传递到我的BrocastReceiver class 时遇到问题。 The problem is the variable I am passing is present on my activity class, not in broadcastReceiver .问题是我传递的变量存在于我的activity class 中,而不是broadcastReceiver中。 I don't know how to get that data into my receiver class.我不知道如何将这些数据输入我的接收器 class。

Activity.java活动.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 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)
    }

As you can see I need to make my activity's place variable available on BroadcastReceiver .如您所见,我需要在BroadcastReceiver上提供活动的place变量。 How can I do this?我怎样才能做到这一点?

Replace:代替:

intent1.putExtra("place", stringNotHere);

With this:有了这个:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM