Отключить сохраненный тип напоминания - PullRequest
0 голосов
/ 04 октября 2018

Я пытаюсь включить напоминания для определенных вещей, элементы находятся в представлении переработчика.

Включение напоминания работает, и оно показывает, как должно.Моя проблема в том, что если пользователь хочет отменить напоминание, оно не отменяет.Я не уверен, почему или что я делаю неправильно.Кто-нибудь может мне помочь?

Адаптер:

 public void onBindViewHolder(@NonNull AssNotiAdapter.MyViewHolder holder, @SuppressLint("RecyclerView") final int position) {
    DecimalFormatSymbols symbols = DecimalFormatSymbols.getInstance();
    symbols.setDecimalSeparator('.');
    DecimalFormat format = new DecimalFormat();
    format.setDecimalFormatSymbols(symbols);
    format.setMaximumFractionDigits(2);
    final FAssessment model = assList.get(position);
    holder.textView_title.setText(model.getDesc());
    holder.textView_date.setText(model.getDate());
    holder.textView_time.setText(model.getTime());
    holder.textView_total.setText("Total: "+Double.toString(model.getTotal()));
    if (selected_position == position) {
        holder.itemView.setBackgroundColor(Color.LTGRAY);
    } else {
        holder.itemView.setBackgroundColor(Color.WHITE);
    }
    holder.itemView.setOnClickListener(v -> {

        notifyItemChanged(selected_position);
        selected_position = position;
        notifyItemChanged(selected_position);
    });
    holder.switchDay.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if(isChecked)
                setReminder(mContext,ReminderReceiver.class,5,model.getDesc());
            else
                cancelReminder(mContext,ReminderReceiver.class,5,model.getDesc());
        }
    });
}

private void setReminder(Context context, Class<?> cls, int sec, String s)
{
    Intent intent = new Intent(context, cls);
    intent.putExtra("TIME",sec);
    intent.putExtra("EDIT",s);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(context, sec, intent,
            PendingIntent.FLAG_UPDATE_CURRENT);
    AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    am.set( AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + (sec * 1000), pendingIntent );
}
private void cancelReminder(Context context, Class<?> cls, int sec, String s)
{
    Intent intent = new Intent(context, cls);
    intent.putExtra("TIME",sec);
    intent.putExtra("EDIT",s);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(context,
            sec, intent, PendingIntent.FLAG_ONE_SHOT);
    AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    if(pendingIntent != null) {
        //assert am != null;
        am.cancel(pendingIntent);
    }
}

и ReminderReciever

public class ReminderReceiver extends BroadcastReceiver {


@Override
public void onReceive(Context context, Intent intent) {
    int Request_Code = intent.getExtras().getInt("TIME",0);
    String r = intent.getExtras().getString("EDIT","");
    showNotification(context, MainActivity.class,
            "You have an Assessment coming up! ", r,Request_Code);
}

public void showNotification(Context context, Class<?> cls, String title, String content,int RequestCode)
{
    Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

    Intent notificationIntent = new Intent(context, cls);
    notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

    TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
    stackBuilder.addParentStack(cls);
    stackBuilder.addNextIntent(notificationIntent);

    PendingIntent pendingIntent = stackBuilder.getPendingIntent(
            RequestCode,PendingIntent.FLAG_UPDATE_CURRENT);

    NotificationManager notificationManager = (NotificationManager)
            context.getSystemService(Context.NOTIFICATION_SERVICE);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        CharSequence name = context.getString(R.string.app_name);
        String description = context.getString(R.string.app_name);
        int importance = NotificationManager.IMPORTANCE_HIGH;
        NotificationChannel channel = new NotificationChannel("my_channel_01", name, importance);
        channel.setDescription(description);
        // Register the channel with the system; you can't change the importance
        // or other notification behaviors after this
        assert notificationManager != null;
        notificationManager.createNotificationChannel(channel);
    }

    NotificationCompat.Builder builder = new NotificationCompat.Builder(context,"my_channel_01");
    Notification notification = builder.setContentTitle(title)
            .setContentText(content).setAutoCancel(true)
            .setSound(alarmSound).setSmallIcon(R.drawable.ic_launcher_background)
            .setContentIntent(pendingIntent).build();


    notificationManager.notify(RequestCode,notification);
}
}

Экраны:

Setting Notification

Здесь я получил код:

Как отправить уведомление, не будучи в сети

Заранее спасибо

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...