当应用程序位于前台时,需要关闭点击通知-android

当应用程序位于前台时,需要关闭点击通知-android,android,android-intent,push-notification,notifications,android-pendingintent,Android,Android Intent,Push Notification,Notifications,Android Pendingintent,我正在用我的应用程序测试推送通知 当应用程序位于前台时: Step 1. Received the notification (in system tray). 2. now, I'm in some other screen than the home screen. 3. Actual Problem: On tap on the notification, it is going to the home screen. 4. Expected: If the

我正在用我的应用程序测试推送通知

当应用程序位于前台时:

Step 1. Received the notification (in system tray). 
     2. now, I'm in some other screen than the home screen.
     3. Actual Problem: On tap on the notification, it is going to the home screen.
     4. Expected: If the app is in the foreground, just I need to cancel on tap of the notification. (No need to swipe.)
当应用程序处于后台/关闭状态时:(工作正常)

尝试在intent中设置启动模式标志。没有帮助。下面是我的代码。请建议解决方案

    Intent resultIntent = new Intent(this, MainActivity.class);
    //resultIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    // resultIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK);

    PendingIntent resultPendingIntent =
            PendingIntent.getActivity(
                    this,
                    0,
                    resultIntent,
                    PendingIntent.FLAG_UPDATE_CURRENT
            );


    NotificationCompat.Builder mBuilder =
            new NotificationCompat.Builder(this);

    mBuilder.setContentIntent(resultPendingIntent);
    mBuilder.setSmallIcon(R.mipmap.ic_launcher);
    mBuilder.setContentTitle(title);
    mBuilder.setContentText(body);
    mBuilder.setAutoCancel(true);
    mBuilder.setStyle(new NotificationCompat.BigTextStyle().bigText(body));
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        mBuilder.setChannelId(TestUtils.creatChanel(this).getId());
    }

    NotificationManager mNotificationManager =
            (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    mNotificationManager.notify(642, mBuilder.build());

在启动程序活动中,您是否尝试过notification manager类cancelAll()方法??
这样,如果启动时已经有通知,那么它将在启动程序活动中自动取消

您是否尝试过notification manager类cancelAll()方法??
这样,如果启动时已经有通知,那么它将自动取消

不确定是否会在点击时取消通知,但因为您担心的是导航错误

我们可以检查应用程序是否在前台,如果应用程序在前台,我们可以阻止通过通知单击打开新活动

//If app is in foreground setting pending intent to null
PendingIntent pendingIntent;
        Intent notificationIntent = new Intent(getApplicationContext(), Main2Activity.class);

        if(isAppInForeground()){
            Log.e("--^","inForeground");
            pendingIntent = null;
        }else{
            Log.e("--^","inBackground");
            notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            pendingIntent = PendingIntent.getActivity(getApplicationContext(), 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        }
添加此函数(源:)

私有布尔值(){
ActivityManager ActivityManager=(ActivityManager)getSystemService(Context.ACTIVITY_服务);
List services=activityManager.getRunningAppProcesses();
布尔值isActivityFound=false;
if(services.get(0.processName)
.equalsIgnoreCase(getPackageName())和&services.get(0).importance==ActivityManager.RunningAppProcessInfo.importance\u前台){
isActivityFound=true;
}
返回isActivityFound;
}

在这种情况下,若通知是在应用程序位于前台时发出的,那个么单击该应用程序将不会执行任何操作。所以,用户只剩下一个选项来滑动它以将其删除。

不确定点击时是否会取消通知,但因为您担心的是导航错误

我们可以检查应用程序是否在前台,如果应用程序在前台,我们可以阻止通过通知单击打开新活动

//If app is in foreground setting pending intent to null
PendingIntent pendingIntent;
        Intent notificationIntent = new Intent(getApplicationContext(), Main2Activity.class);

        if(isAppInForeground()){
            Log.e("--^","inForeground");
            pendingIntent = null;
        }else{
            Log.e("--^","inBackground");
            notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            pendingIntent = PendingIntent.getActivity(getApplicationContext(), 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        }
添加此函数(源:)

私有布尔值(){
ActivityManager ActivityManager=(ActivityManager)getSystemService(Context.ACTIVITY_服务);
List services=activityManager.getRunningAppProcesses();
布尔值isActivityFound=false;
if(services.get(0.processName)
.equalsIgnoreCase(getPackageName())和&services.get(0).importance==ActivityManager.RunningAppProcessInfo.importance\u前台){
isActivityFound=true;
}
返回isActivityFound;
}

在这种情况下,若通知是在应用程序位于前台时发出的,那个么单击该应用程序将不会执行任何操作。因此,用户只剩下一个选项可以将其滑动以删除。

您可以使用“关闭”按钮创建自定义通知,以使用RemoteView关闭通知

//使用RemoteView创建通知:

RemoteViews remoteViews= new RemoteViews(getApplicationContext().getPackageName(), R.layout.your_custom_notification);
Intent closeIntent = new Intent(context, CloseNotificationService.class);
hangUpIntent.setAction("close");

PendingIntent pendingCloseIntent = PendingIntent.getBroadcast(this, 0, closeNotification, PendingIntent.FLAG_UPDATE_CURRENT);

remoteViews.setOnClickPendingIntent(R.id.cancel_notification, pendingCloseIntent);

// create notification here..
Notification customNotification = new NotificationCompat.Builder(context, CHANNEL_ID)
    .setSmallIcon(R.drawable.notification_icon)
    .setStyle(new NotificationCompat.DecoratedCustomViewStyle())
    .setCustomContentView(remoteViews)
    .build();
单击关闭按钮后,它将重定向到服务类:

public class CloseNotificationService extends IntentService {

        /**
         * Creates an IntentService.  Invoked by your subclass's constructor.
         */
        public CloseNotificationService() {
            super("notificationIntentService");
        }

        @Override
        protected void onHandleIntent(@Nullable Intent intent) {
            switch (intent.getAction()) {

                case "close":
                    Handler hangUpHandler = new Handler(Looper.getMainLooper());
                    hangUpHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            NotificationManager notifManager = 
                                    (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
                            notifManager.cancel(notificationId); // get notification id from intent.
                        }
                    });
                    break;
            }
        }
    }

有关RemoteView的更多信息,请访问google开发者官方网站

您可以使用“关闭”按钮创建自定义通知,以使用RemoteView关闭通知

//使用RemoteView创建通知:

RemoteViews remoteViews= new RemoteViews(getApplicationContext().getPackageName(), R.layout.your_custom_notification);
Intent closeIntent = new Intent(context, CloseNotificationService.class);
hangUpIntent.setAction("close");

PendingIntent pendingCloseIntent = PendingIntent.getBroadcast(this, 0, closeNotification, PendingIntent.FLAG_UPDATE_CURRENT);

remoteViews.setOnClickPendingIntent(R.id.cancel_notification, pendingCloseIntent);

// create notification here..
Notification customNotification = new NotificationCompat.Builder(context, CHANNEL_ID)
    .setSmallIcon(R.drawable.notification_icon)
    .setStyle(new NotificationCompat.DecoratedCustomViewStyle())
    .setCustomContentView(remoteViews)
    .build();
单击关闭按钮后,它将重定向到服务类:

public class CloseNotificationService extends IntentService {

        /**
         * Creates an IntentService.  Invoked by your subclass's constructor.
         */
        public CloseNotificationService() {
            super("notificationIntentService");
        }

        @Override
        protected void onHandleIntent(@Nullable Intent intent) {
            switch (intent.getAction()) {

                case "close":
                    Handler hangUpHandler = new Handler(Looper.getMainLooper());
                    hangUpHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            NotificationManager notifManager = 
                                    (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
                            notifManager.cancel(notificationId); // get notification id from intent.
                        }
                    });
                    break;
            }
        }
    }
有关RemoteView的更多信息,您可以参考google开发者官方网站,而不是此网站:

Intent resultIntent = new Intent(this, MainActivity.class);
这样做:

Intent resultIntent = getPackageManager().getLaunchIntentForPackage("your.package.name");
并将其放入您的
通知中。如果应用程序尚未运行,这将启动该应用程序,否则它只会将应用程序的任务以用户上次使用它时的任何状态带到前台。如果用户已经在应用程序中(即:在另一个屏幕上),当用户单击
通知时,这将不会起任何作用

应该正是您想要的。

而不是:

Intent resultIntent = new Intent(this, MainActivity.class);
这样做:

Intent resultIntent = getPackageManager().getLaunchIntentForPackage("your.package.name");
并将其放入您的
通知中。如果应用程序尚未运行,这将启动该应用程序,否则它只会将应用程序的任务以用户上次使用它时的任何状态带到前台。如果用户已经在应用程序中(即:在另一个屏幕上),当用户单击
通知时,这将不会起任何作用



应该正是您想要的。

点击通知后,我需要取消。所以你提到的方式不起作用:(我需要取消点击通知。所以你提到的方式不起作用:(你想总是取消通知吗?当应用程序在前台时取消通知的目的是什么?不。我不想总是取消通知。通知的目的不应该影响应用程序导航。如果我在屏幕3中,点击通知,我现在会进入主屏幕。如果导航不应该影响应用程序导航,那么你没有o当您在应用程序中时取消所有通知。是否要始终取消通知?当应用程序位于前台时取消通知的目的是什么?否。我不想始终取消通知。通知的目的不应影响应用程序导航。如果在屏幕3中输入im并点击通知,我现在将进入主屏幕。如果vigation不应影响应用程序导航,然后您必须在应用程序中取消所有通知。这将不起作用。根据@Samp功能,如果您在前台,收到通知,然后关闭应用程序,然后点击该通知,则不会发生任何事。由于pen原因,它不会打开应用程序ding intent为空。@Nik yes.。在这种情况下,我们需要找到其他解决方案。thanks@Nik是的。你是对的。此解决方案将影响背景溶液。(At)Naitik感谢您的尝试。有没有办法设置我要传递的目的标志?是的,最好使用RemoteView将按钮置于通知中。这将不起作用。根据@Samp功能,如果您在前台,收到通知,然后关闭应用程序,然后点击该通知,则什么都没有g将发生。由于挂起的意图为空,它将不会打开应用程序。@Nik yes..在这种情况下,我们需要