java - 前台通知操作不发送广播

标签 java android notifications broadcastreceiver

我的应用程序有一项全职运行的服务。当应用程序在屏幕上时,服务在后台运行;当应用程序关闭屏幕或关闭时,服务将通过前台通知运行。

在此通知中,我有一个发送广播的操作按钮。这个按钮没有发送广播,我不知道为什么,因为我测试了接收器并且接收器正在工作。

我的通知操作或我的接收器有问题吗?

服务代码:

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

}

最佳答案

已解决... 为了使广播接收器在独立于 Activity 的服务上运行,我必须将广播类设为静态并将其注册到 list 上。

广播:

public static class TimerServiceReceiver extends BroadcastReceiver{
    private String TAG = TimerService.class.getSimpleName();

    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!");
                        break;
                }
            }
        }
    }
}

manifest.xml:

     <receiver
        android:name=".services.TimerService$TimerServiceReceiver"
        android:enabled="true"
        android:exported="true"
        android:label="RestartServiceWhenStopped">
        <intent-filter>
            <action android:name="TIMER_START"/>
            <action android:name="TIMER_PAUSE"/>
            <action android:name="TIMER_STOP"/>
        </intent-filter>
    </receiver>

关于java - 前台通知操作不发送广播,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54747691/

相关文章:

javascript - 尝试权限请求通知错误 Javascript

java - 在 SWT 应用程序中使用 styledText

java - 泛型方法调用

java - 简单的 System.out 打印

Android getParent() 为 null 但已设置 parentActivityName

android - 如何找出Android应用程序中未使用哪些资源

java - 将 Matrix4f 加载到 FloatBuffer 中,以便我的着色器可以使用它

java - HashMap 在 Android 中不稳定

Android:折叠通知中的额外间距

java - Android 更新通知并检测它何时不再存在