如何在 RingerMode 更改时取消通知

How to cancel a Notification when RingerMode changed

我正在尝试制作一个状态栏通知,当应用程序处于活动状态时通知,当应用程序处于非活动状态时通知取消。 当用户通过单击应用程序中的打开按钮打开应用程序时,我收到了通知。当用户以同样的方式关闭应用程序时,我也收到了取消通知。 我遇到的问题是,用户只需调高铃声音量即可切换应用程序,但以这种方式关闭应用程序时,通知不会取消。 我收到错误:

System services not available to Activities before onCreate()

主要活动:

buttonToggleDetect.setOnClickListener(new View.OnClickListener() {
        @Override
        // when the main button is clicked
        public void onClick(View v) {
            setDetectEnabled(!detectEnabled);
            mTracker.send(new HitBuilders.EventBuilder()
                    .setCategory("Home")
                    .setAction("Share")
                    .build());

            if (isServiceRunning()){
                showStatusBarIcon("App","App Active",true);
            }
            else showStatusBarIcon("App","App InActive", false);
        }

.

public void showStatusBarIcon(String notificationTitle, String notifactionMessage, boolean serviceActive){
    NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    Notification notification = new Notification(R.drawable.info_icon,"App Active",System.currentTimeMillis());
    Intent notifactionIntent = new Intent(this,MainActivity.class);
    PendingIntent pendingIntent = PendingIntent.getActivity(this,0,notifactionIntent,0);

    notification.setLatestEventInfo(MainActivity.this, notificationTitle, notifactionMessage, pendingIntent);
    if (serviceActive) {
        notificationManager.notify(9999, notification);
    }
    else {
        notificationManager.cancel(9999);
    }
}

RingerModeStateReceiver class

public class RingerModeStateReceiver extends BroadcastReceiver {

MainActivity mainActivity = new MainActivity();

public RingerModeStateReceiver() {
}

@Override // when the android sends a broadcast message that the RingerModeState has changed
public void onReceive(Context context, Intent intent) {
    // TODO: This method is called when the BroadcastReceiver is receiving


    AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);


    int ringMode = audioManager.getRingerMode();
    if (ringMode == AudioManager.RINGER_MODE_NORMAL){
        context.stopService(new Intent(context, CallDetectService.class));
        mainActivity.showStatusBarIcon("App","App InActive", false);
    }
    //throw new UnsupportedOperationException("Not yet implemented");
}

}

谁能帮帮我,看看我哪里出错了?谢谢

您需要在关闭应用程序之前删除通知。

您可以从应用程序的 onDestroy 甚至服务中执行此操作。

问题是 "showStatusBarIcon" 无法从您需要使用上下文的 broadcastReciever 调用。

从另一个 post 我找到了答案。 在广播接收器 class 中,我替换了

mainActivity.showStatusBarIcon("App","App InActive", false);

 NotificationManager notifactionManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
        notifactionManager.cancel(9999);

这里是 link answer in other post

我搜索 "how to cancel notifaction from broadcast" 找到 post