Как остановить службу переднего плана с использованием Broadcast Receiver - PullRequest
0 голосов
/ 23 января 2020

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

Intent intent = new Intent(this, MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);

        Intent broadcastIntent = new Intent(this, NotificationReceiver.class);
        broadcastIntent.putExtra("toastMessage", "Test message");
        PendingIntent actionIntent = PendingIntent.getBroadcast(this, 0, broadcastIntent, PendingIntent.FLAG_UPDATE_CURRENT);

        String channelId = "fcm_default_channel";
        Bitmap largeIcon = BitmapFactory.decodeResource(getResources(), R.drawable.notification_uploading);
        NotificationCompat.Builder notificationBuilder =
                new NotificationCompat.Builder(this, channelId)
                        .setSmallIcon(R.drawable.animation_wifi)
                        .setContentTitle("Upload Photos")
                        .setContentText("1 photo uploading")
                        .setContentIntent(pendingIntent)
                        .addAction(R.drawable.icon_back_black_arrow, "Cancel", actionIntent);


        startForeground(1111, notificationBuilder.build());

У нее есть кнопка отмены, которая вызывает мой Broadcast Receiver. Как мне остановить службу переднего плана внутри класса приемника вещания?

public class NotificationReceiver extends BroadcastReceiver {
    private static final String TAG = "NotificationReceiver";
    @Override
    public void onReceive(Context context, Intent intent) {
        String message = intent.getStringExtra("toastMessage");
        Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
        //When the foreground notification cancel button is clicked, this method is called
    }
}

1 Ответ

1 голос
/ 23 января 2020

метод stopForeground() может остановить службу, но он является частью класса Service. он не может быть вызван ни получателем.

Вот два решения, вы можете понять, что.

одно решение в вашем классе обслуживания регистрирует BroadcastReceiver, когда цель BroadcastReceiver получает сообщение, отправляет широковещательную рассылку получателю услуги.

//the service class
private final BroadcastReceiver closeService = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            // Bla bla bla
            stopForeground(NOTIF_ID);
    };
IntentFilter filter = new IntentFilter(""my.close.service"");
registerReceiver(mYReceiver, iFilter);

public class NotificationReceiver extends BroadcastReceiver {
    private static final String TAG = "NotificationReceiver";
    @Override
    public void onReceive(Context context, Intent intent) {
        String message = intent.getStringExtra("toastMessage");
        Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
        // here to send it to service
       sendBroadcast(new Intent("my.close.service"))
    }
}

другое решение - в вещании, перезапустите службу, в методе onStartCommad, в соответствии с действием по ее закрытию.

public class NotificationReceiver extends BroadcastReceiver {
    private static final String TAG = "NotificationReceiver";
    @Override
    public void onReceive(Context context, Intent intent) {
        String message = intent.getStringExtra("toastMessage");
        Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
        // here to restart the service
       startService(new Intent(this, YourService.class).setAction("STOP_ACTION"));
    }
}

// in the Service.java onStartCommand method, check the action and stop it.
public void onStartCommand(){
  if(intent.getAction() != null && 
   intent.getAction().equals("STOP_ACTION")) {
     stopForeground(true);
  }
}

В конце концов, если вы знакомы с EventBus, вы можете использовать его для отправки события службе напрямую. или вы можете определить BroadcastReceiver как внутренний класс в Сервисе, тогда вы также можете вызвать его напрямую

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