Search code examples
javaandroidbroadcastreceiverandroid-notifications

Pass data from Activity to Broadcast Receiver with Intent


I am scheduling a notification at a particular time via BroacastReciever. I want to pass data from notification click to activity's newIntent method. So far everything works well as the notifications come through. However, I have an issue passing data from activity to my BrocastReceiver class. The problem is the variable I am passing is present on my activity class, not in broadcastReceiver. I don't know how to get that data into my receiver class.

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

As you can see I need to make my activity's place variable available on BroadcastReceiver. How can I do this?


Solution

  • Replace :

    intent1.putExtra("place", stringNotHere);
    

    With this:

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