В моем приложении есть служба, которая работает полный рабочий день.Когда приложение на экране, сервис работает в фоновом режиме;и когда приложение выключено или закрыто, служба запускается с уведомлением переднего плана.
В этом уведомлении у меня есть кнопка действия, которая отправляет широковещательную рассылку.Эта кнопка не отправляет широковещательную рассылку, и я не знаю почему, потому что я проверил приемник, и приемник работает.
Что-то не так с моим уведомлением или моим получателем?
Сервисный код:
public class TimerService extends Service {
private String TAG = TimerService.class.getSimpleName();
private TimerServiceReceiver receiver;
private NotificationManager mNotificationManager;
private NotificationCompat.Builder mBuilder;
Notification notification;
private boolean runningBackground;
public TimerService() {
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
createNotificationChannel();
mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
if(runningBackground){
registerBroadcastReceiver();
Log.v(TAG, "Service Broadcast registered.");
createNotification();
}else{
mNotificationManager.cancel(ID_SERVICE);
}
return START_NOT_STICKY;
}
...
//=== NOTIFICATION ===/
private void createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
CharSequence name = getString(R.string.channel_name);
String description = getString(R.string.channel_description);
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance);
channel.setDescription(description);
NotificationManager notificationManager = getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
}
}
private void createNotification(){
mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Intent intent = new Intent(this, ExecuteExerciseActivity.class);
intent.putExtra("id_execution", idExecution);
intent.putExtra("id_exercise", idExercise);
intent.putExtra("position", position);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addNextIntentWithParentStack(intent);
PendingIntent pendingIntent = stackBuilder.getPendingIntent(ID_SERVICE, PendingIntent.FLAG_UPDATE_CURRENT);
//Action Buttons & Intents
Intent pauseIntent = new Intent(this, TimerServiceReceiver.class);
pauseIntent.setAction(TIMER_PAUSE);
PendingIntent pausePendingIntent = PendingIntent.getBroadcast(this, 0, pauseIntent, PendingIntent.FLAG_CANCEL_CURRENT);
mBuilder = new NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle(getResources().getString(R.string.timer))
.setContentText("00:00:00")
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setSmallIcon(R.mipmap.ic_launcher)
.setPriority(PRIORITY_MIN)
.setCategory(NotificationCompat.CATEGORY_SERVICE)
.setContentIntent(pendingIntent)
.setAutoCancel(true)
.addAction(R.drawable.ntf_pause, getString(R.string.pause_timer), pausePendingIntent);
notification = mBuilder.setOngoing(true)
.build();
startForeground(ID_SERVICE, notification);
}
private void updateNotificationText(String s){
if(mBuilder != null && notification != null){
mBuilder.setContentText(s);
mNotificationManager.notify(ID_SERVICE, mBuilder.build());
}
}
@Override
public void onDestroy() {
super.onDestroy();
Log.v(TAG, "ondestroy!");
...
if(receiver != null) {
unregisterReceiver(receiver);
Log.v(TAG, "Service Broadcast unregistered.");
}
}
//=== BROADCAST RECEIVER ===/
public class TimerServiceReceiver extends BroadcastReceiver{
public TimerServiceReceiver() {
}
@Override
public void onReceive(Context context, Intent intent) {
Log.v(TAG, "Message received by Service Broadcast!");
if(intent != null){
String action = intent.getAction();
Bundle extras = intent.getExtras();
//Updates tvTimer
if(action != null){
switch(action){
case TIMER_PAUSE:
Log.v(TAG, "Notification sent Pause command!");
timerPause = true;
startForegroundService(new Intent(context, TimerService.class));
break;
}
}
}
}
}
private void registerBroadcastReceiver() {
receiver = new TimerServiceReceiver();
IntentFilter statusIntentFilter = new IntentFilter(TIMER_SERVICE_BROADCAST);
statusIntentFilter.addAction(TIMER_START);
statusIntentFilter.addAction(TIMER_PAUSE);
statusIntentFilter.addAction(TIMER_STOP);
// Registers the DownloadStateReceiver and its intent filters
registerReceiver(receiver, statusIntentFilter);
}
}