How to Pass Data from Fragment to Broadcast Receiver with Alarm Manager

Viewed 535

In My Application inside a Fragment I set an Alarm Event using Alarm Manager which Triggers a Broadcast Receiver when the Alarm Event Occurred.The Problem is i want to pass data to that Broadcast Receiver Every Time it gives 0 as the default value.I have tried all the possible solution from the google but it doesn't work for me. The Method inside Fragment is as follows:

public static final String EVENT = "EventData";
public void addToAlarmManager(long id) {
        AlarmManager alarmManager = (AlarmManager) getActivity().getSystemService(getContext().ALARM_SERVICE);
        Intent eventIntent = new Intent(getContext(), TimeEventReciever.class);
        eventIntent.putExtra(EVENT,id);
        PendingIntent eventPendingIntent = PendingIntent.getBroadcast(getContext(), 1, eventIntent, PendingIntent.FLAG_UPDATE_CURRENT);
    alarmManager.setExact(AlarmManager.RTC_WAKEUP, selectedTime.longValue(), eventPendingIntent);
}

TimeEventReciever class as follows:

public class TimeEventReciever extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        long eventId=intent.getLongExtra(EVENT,0);
       Log.e("event","event id : "+String.valueOf(eventId));
}
}
2 Answers

Try this may help you

Put data in intent you are using in pending intent as Extras. You will get this intent in onReceive Method of BroadCast receiver. Try to define Pending intent as below.

PendingIntent eventPendingIntent = PendingIntent.getBroadcast(activity, 0, eventIntent,PendingIntent.FLAG_CANCEL_CURRENT);

Use Below Step to pass data from fragment to Broadcast receiver using Alarm Manager

Step-1 : Add Value in intent of Broadcast Receiver Class File.

   Intent intent = new Intent(context, MyBroadcastReceiver.class);

    intent.putExtra("rId", currentReminder.getId());
    intent.putExtra("rTitle", currentReminder.getrTitle());
    intent.putExtra("rDesc", currentReminder.getrDesc());
    intent.putExtra("rDate", currentReminder.getrDate());
    intent.putExtra("rTime", currentReminder.getrTime());
    intent.putExtra("rCallFor", currentReminder.getrType());
    intent.putExtra("rName", currentReminder.getCallLogBean().getCallName());
    intent.putExtra("rMobile", currentReminder.getCallLogBean().getCallNumber());

Step-2 : Then pass this intent object using Pending intent with the help of below code.

Note: Write down below code immediate after intent.putExtra

  PendingIntent pendingIntent = PendingIntent.getBroadcast(
            this.getActivity(), currentReminder.getId(), intent, 0);
    AlarmManager alarmManager = (AlarmManager) context.getSystemService(ALARM_SERVICE);

alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, reminderTime,
                repeateInterval, pendingIntent);

NOTE: Step-1 and Step-2: Write down in your fragment or activity which you used as per your requirement.

=================================================================================

Step-3 : Create BrodcastReceiver File and add below code. This help you retrieve data from intent in broadcast receiver

public class MyBroadcastReceiver extends BroadcastReceiver {
public  static  MediaPlayer mp;
private static final int NOTIFICATION_ID = 0;
private NotificationManager mNotifyManager;
private NotificationCompat.Builder build;
String TAG="BrodcastReceiver";
int rId;
String rTitle,rDesc,rDate,rTime,rCallFor,rName,rMobile;
PrefBean prefBean=new PrefBean();
SharedPrefrenceManager sharedPrefrenceManager;
ReminderBean currentReminder;

@Override
public void onReceive(Context context, Intent intent) {
    rId= intent.getIntExtra("rId",0);
    rTitle= intent.getStringExtra("rTitle");
    rDesc = intent.getStringExtra("rDesc");
    rDate = intent.getStringExtra("rDate");
    rTime = intent.getStringExtra("rTime");
    rCallFor = intent.getStringExtra("rCallFor");
    rName = intent.getStringExtra("rName");
    rMobile = intent.getStringExtra("rMobile");
    CallLogBean callLogBean=new CallLogBean();
    callLogBean.setCallName(rName);
    callLogBean.setCallNumber(rMobile);
    Log.e(TAG, "onReceive: "+rId );



    NotificationManager manager = (NotificationManager) context.getSystemService(NOTIFICATION_SERVICE);
        mp = MediaPlayer.create(context, R.raw.alarm);
        mp.start();
        Toast.makeText(context, "Alarm....", Toast.LENGTH_LONG).show();
    sharedPrefrenceManager = new SharedPrefrenceManager(Const.FILE_NAME,context);
    prefBean=sharedPrefrenceManager.getSharedPreferences();
    String remindAs=prefBean.getShowReminderAs();
    Log.e(TAG, "onReceive: "+remindAs );
    if(remindAs.equals(Const.ALARAM)){

        startNotification(context,intent);
    }else{
        startNotification(context,intent);
    }


}


private void startNotification(Context context, Intent intent) {
    RemoteViews notificationLayout = new RemoteViews(context.getPackageName(), R.layout.notification_small);
    RemoteViews notificationLayoutExpanded = new RemoteViews(context.getPackageName(), R.layout.notification_large);


    Intent notificationIntent = new Intent(context, HomeActivity.class);

    notificationLayout.setTextViewText(R.id.notification_title,rTitle);

    notificationLayoutExpanded.setTextViewText(R.id.not_txt_title,rTitle);
    notificationLayoutExpanded.setTextViewText(R.id.not_txt_desc,rDesc);
    notificationLayoutExpanded.setTextViewText(R.id.not_txt_callfor,rCallFor);
    notificationLayoutExpanded.setTextViewText(R.id.not_txt_name,rName);


    //notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
      //      | Intent.FLAG_ACTIVITY_SINGLE_TOP);
    notificationIntent.putExtra("rId",rId);
    notificationIntent.putExtra("rTitle",rTitle);
    notificationIntent.putExtra("rDesc",rDesc);

    Log.e(TAG, "startNotification:\n  "+rId );
    PendingIntent pendingIntent = PendingIntent.getActivity(context, rId,
            notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);

    mNotifyManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
    build = new NotificationCompat.Builder(context);
    build.setContentTitle(rTitle)
            .setContentText(rDesc)
            .setChannelId(rId+"")
            .setAutoCancel(true)
            .setStyle(new NotificationCompat.DecoratedCustomViewStyle())
            .setCustomContentView(notificationLayout)
            .setCustomBigContentView(notificationLayoutExpanded)
            .setContentIntent(pendingIntent)
            .setSmallIcon(R.drawable.ic_calendar);

    // Since android Oreo notification channel is needed.
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        NotificationChannel channel = new NotificationChannel(rId+"" ,
                "Call Reminder",
                NotificationManager.IMPORTANCE_HIGH);
        channel.setDescription("With sound");
        channel.setSound(null,null);
        channel.enableLights(false);
        channel.setLightColor(Color.BLUE);
        channel.enableVibration(true);
        mNotifyManager.createNotificationChannel(channel);

    }


    mNotifyManager.notify(rId, build.build());

}
Related