Как передать данные из фрагмента в широковещательный приемник с помощью Alarm Manager - PullRequest
0 голосов
/ 26 февраля 2020

В моем приложении внутри фрагмента я устанавливаю событие тревоги с помощью диспетчера тревоги, который запускает широковещательный приемник при возникновении события тревоги. Проблема в том, что я хочу передавать данные этому широковещательному приемнику каждый раз, когда он дает 0 в качестве значения по умолчанию. Я перепробовал все возможные решения от Google, но он не работает для меня. Метод внутри фрагмента выглядит следующим образом:

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 выглядит следующим образом:

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 ]

1 голос
/ 26 февраля 2020

Попробуйте, это может помочь вам

Поместите данные в намерение, которое вы используете, в качестве намерения в качестве Доп. Вы получите это намерение в методе onReceive приемника BroadCast. Попробуйте определить ожидающее намерение, как показано ниже.

PendingIntent eventPendingIntent = PendingIntent.getBroadcast(activity, 0, eventIntent,PendingIntent.FLAG_CANCEL_CURRENT);
0 голосов
/ 26 февраля 2020

Используйте шаг ниже для передачи данных из фрагмента в приемник вещания с помощью диспетчера аварийных сигналов

Шаг-1: Добавление значения в файл класса приемника вещания.

   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());

Шаг-2: Затем передайте этот объект намерения, используя Ожидание намерения, с помощью приведенного ниже кода.

Примечание. Запишите код ниже сразу после 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);

ПРИМЕЧАНИЕ: Шаг-1 и Шаг-2: Запишите в своем фрагменте или деятельности, которую вы использовали согласно вашему требованию.

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

Шаг 3: создание файла BrodcastReceiver и добавьте ниже код. Это поможет вам извлечь данные из намерения в широковещательном приемнике

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());

}
...