Кнопки действий в уведомлении отображаются, но при нажатии не работает - PullRequest
0 голосов
/ 10 июля 2019

Я использую сервис для запуска медиаплеера, как только появится уведомление, и затем остановил сервис, когда нажата кнопка действия.Служба начинается нормально.Но служба не останавливается при нажатии кнопки действия.

Это мой конструктор уведомлений

public NotificationCompat.Builder getReminderNotification(String title,String message,PendingIntent intent1){

    return new NotificationCompat.Builder(getApplicationContext(),reminderChannelID)
            .setContentTitle(title)
            .setContentText(message)
            .setSmallIcon(R.drawable.ic_medicine)
            .setColor(getResources().getColor(R.color.colorPrimary))
            .setOngoing(true)
            .addAction(R.drawable.ic_arrow_back,"OK",intent1);
}

public void cancelNotification() {
   NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    mNotificationManager.cancel(1); // Notification ID to cancel
}

public void startMyService(){
    startService(new Intent(this, TimerService.class));
}

public void stopMyService(){
    stopService(new Intent(this,TimerService.class));
}

Это мой получатель напоминания:

public class ReminderReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
    NotificationHelper notificationHelper = new NotificationHelper(context);
    Intent newIntent = new Intent(context,DismissReminderReceiver.class);
    newIntent.putExtra("action","stop");
    PendingIntent intent1 = PendingIntent.getBroadcast(context,0,newIntent,0);
    Bundle extras = intent.getExtras();

    String title=extras.getString("title");
    String message=extras.getString("message");

        NotificationCompat.Builder builder = notificationHelper.getReminderNotification(title, message,intent1);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            context.startForegroundService(new Intent(context.getApplicationContext(),TimerService.class));
        }else {
            notificationHelper.startMyService();
        }
        notificationHelper.getManager().notify(1, builder.build());

}}

Этомой код для отклонения уведомления

public class DismissReminderReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
    System.out.println("Here");
    Bundle extras = intent.getExtras();
    String action = extras.getString("action");
    System.out.println(action);
    if (action.equals("stop")) {
        NotificationHelper notificationHelper = new NotificationHelper(context);
        notificationHelper.stopMyService();
        notificationHelper.cancelNotification();
    }
}}

А это мой сервис:

public class TimerService extends Service {

public Context context = this;
public Handler handler = null;
public Runnable runnable = null;
MediaPlayer mediaPlayer;public TimerService(){}

@Override
public IBinder onBind(Intent intent) {
    return null;
}

@Override
public void onCreate() {
System.out.println("Service Started");
    mediaPlayer=MediaPlayer.create(context, Settings.System.DEFAULT_RINGTONE_URI);
    handler = new Handler();
    runnable = new Runnable() {
        @Override
        public void run() {
            mediaPlayer.start();
        }
    };
    handler.postDelayed(runnable,0);
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    return super.onStartCommand(intent, flags, startId);
}

@Override
public void onDestroy() {
    handler.removeCallbacks(runnable);
    mediaPlayer.stop();
}}

1 Ответ

0 голосов
/ 10 июля 2019

Я также не вижу, где вы регистрируете получателя - если вы делаете это в манифесте, убедитесь, что он там с соответствующим действием (и раздел приемника здесь для начала).

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