点击操作按钮后通知未被删除,即使已提供通知ID

4
我正在发送一个通知,其中有2个操作按钮,分别是“接受”和“拒绝”。
我正在遵循这个Github repo
当用户点击“接受”时,会检查某些条件,并相应地执行逻辑。
更新2.0-问题在于,点击“接受”按钮后,操作成功进行,但通知未从状态栏消失,因为此处生成的id:m =(new Random()).nextInt(10000); 与此处不同:actionIntent.putExtra(“id”,NotificationARBroadcastReceiver.m); 每次都不同!
以下是通知的代码:
Intent notificationIntent = new Intent(getBaseContext(), NotificationARBroadcastReceiver.class);
notificationIntent.putExtra(NotificationARBroadcastReceiver.NOTIFICATION, getNotificationNewRequestService());
PendingIntent pendingIntent = PendingIntent.getBroadcast(getBaseContext(), m, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, 0, pendingIntent);

这里是getNotificationNewRequestService():
private Notification getNotificationNewRequestService() {

        mBuilder =
                new NotificationCompat.Builder(getBaseContext())
                        .setSmallIcon(R.mipmap.app_icon_1)
                        .setContentTitle("Title")
                        .setContentText("text...");

        Intent resultIntent = new Intent(getBaseContext(), Profile.class);

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

        // for action button
        Intent actionIntent = new Intent(getBaseContext(), MyBroadcastSender.class);
        actionIntent.putExtra("id", NotificationARBroadcastReceiver.m);
        PendingIntent actionPendingIntent = PendingIntent
                .getBroadcast(getBaseContext(),
                        0, actionIntent, PendingIntent.FLAG_UPDATE_CURRENT);

        mBuilder.setAutoCancel(true);
        mBuilder.setContentIntent(resultPendingIntent);
        mBuilder.addAction(R.drawable.ic_accepted_request_black_24dp, "Accept", actionPendingIntent);
        mBuilder.addAction(R.drawable.ic_close_black_24dp, "Reject", null);

        return mBuilder.build();
    }

这是 NotificationARBroadcastReceiver.java 文件:

public class NotificationARBroadcastReceiver extends BroadcastReceiver {

    public static String NOTIFICATION = "notification";
    public static NotificationManager mNotifyMgr;
    public static int m;

    @Override
    public void onReceive(Context context, Intent intent) {

        m = (new Random()).nextInt(10000);
        Log.d("mMain", String.valueOf(m));

        mNotifyMgr =
                (NotificationManager) context.getSystemService(NOTIFICATION_SERVICE);

        Notification notification = intent.getParcelableExtra(NOTIFICATION);
        notification.defaults |= Notification.DEFAULT_SOUND;
        notification.defaults |= Notification.DEFAULT_VIBRATE;
        mNotifyMgr.notify(m, notification);

    }
}

这是MyBroadcastSender.java文件:

public class MyBroadcastSender extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {

        Toast.makeText(context, "Broadcast Received by MyBroadcastSender.", Toast.LENGTH_SHORT).show();

        int id = intent.getIntExtra("id", 1);

        // send back to your class
        Intent newIntent = new Intent();
        newIntent.setAction(context.getString(R.string.broadcast_id));
        newIntent.putExtra("id1", id);
        context.sendBroadcast(newIntent);
        context.sendBroadcast(new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS));
        Toast.makeText(context, "Broadcast sent back.", Toast.LENGTH_SHORT).show();

    }
}

这是MyBroadcastReceiver.java文件:

// BroadcastReceiver
    public class MyBroadcastReceiver extends BroadcastReceiver {

        public MyBroadcastReceiver(){
            super();
        }

        @Override public void onReceive(Context context, Intent intent) {

            int id2 = intent.getIntExtra("id1", 1);

            if (intent.getAction() != null && intent.getAction().equals(getString(R.string.broadcast_id))) {

                NotificationARBroadcastReceiver.mNotifyMgr.cancel(id2);

                Intent intent1 = new Intent(MyService.this, MainActivity.class);
                intent1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent1);

                Toast.makeText(context, "Broadcast received by MyBroadcastReceiver. Now, you can perform actions.",
                        Toast.LENGTH_SHORT).show();

            } else {
                Toast.makeText(context, "Intent is null.", Toast.LENGTH_SHORT).show();
            }
        }
    }

getNotificationNewRequestService()中,我将通知ID作为额外信息放入"id"中,然后在MyBroadcastSender.java中,我将其作为int id = intent.getIntExtra("id", 1);获取,然后再次放入newIntent.putExtra("id1", id);,最后在MyBroadcastReceiver.java中获取它作为int id2 = intent.getIntExtra("id1", 1);,并尝试使用它作为NotificationARBroadcastReceiver.mNotifyMgr.cancel(id2);来删除通知。

很抱歉这么多代码,但它们都是必要的。

我想知道的是:如何将同一通知ID从NotificationARBroadcastReceiver.java(这是一个单独的java文件)传递到MyBroadcastReceiver(这是MyService.java中的内部类)?

更新1.0-当我打印出mmMainidid1的值时,发生了什么:

D/m: 0
D/mMain: 9994
D/id: 0
D/id1: 0

你尝试过这个吗:https://dev59.com/MGct5IYBdhLWcg3wsfkZ - M.Waqas Pervez
@M.WaqasPervez 哦,是的,我已经尝试过了。这就是我正在使用的逻辑来尝试删除通知。 - Hammad Nasir
尝试打印您的变量:midid1id2 - rupinderjeet
@rupinderjeet请查看编辑后的问题。 - Hammad Nasir
2个回答

2
假设getNotificationService() == getNotificationNewRequestService()。看起来 NotificationARBroadcastReceiver 在构建和显示通知之前没有被调用。
你最好在创建通知时生成通知 id,然后将其添加到意图中。同时,无需进行任何操作。
因此,请在 NotificationARBroadcastReceiver.receive() 中调用 getNotificationNewRequestService() 并确保通知 id 匹配。

你最好在创建通知时生成通知ID,并将其添加到意图中,这样你就不需要再进行其他操作了。这句话的意思是建议在创建通知时直接生成通知ID并将其添加到意图中,而无需进行其他操作。以下是根据此建议编写的示例代码:// 生成通知ID int notificationId = 1; // 创建通知 NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID) .setSmallIcon(R.drawable.notification_icon) .setContentTitle("My notification") .setContentText("Hello World!") .setPriority(NotificationCompat.PRIORITY_DEFAULT); // 将通知ID添加到意图中 Intent intent = new Intent(this, MainActivity.class); intent.putExtra("notificationId", notificationId); PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0); builder.setContentIntent(pendingIntent); // 显示通知 NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this); notificationManager.notify(notificationId, builder.build()); - Hammad Nasir
在生成意图之前,您正在将ID添加到意图中,就像我之前说的那样,在NotificationARBroadcastReceiver.recieve()中生成您的ID并将其传递给getNotificationNewRequestService(id),然后调用notify(id, notif)。您的问题是在生成ID之前构建通知。 - siliconeagle
问题在于getNotificationNewRequestService()在一个Service中,而NotificationARBroadcastReceiver是一个单独的文件。在调用notify(id, notif)之前,我该如何将NotificationARBroadcastReceiver.recieve()中生成的id传递给getNotificationNewRequestService() - Hammad Nasir
将一个整数资源用作ID。在“values”文件夹下的“integers.xml”文件中添加<integer name="notif_id"></integer>。您还可以使用静态变量在另一个文件中访问它。 - rupinderjeet
我说得很清楚,你应该能看出错误在哪里。抱歉我不能为你编写代码。如果你有问题就问吧。 - siliconeagle
显示剩余2条评论

2

编辑

移动:

m = (new Random()).nextInt(10000);

之前:

actionIntent.putExtra("id", NotificationARBroadcastReceiver.m); // this will be 'm'

结果:

int m = (new Random()).nextInt(10000);
Intent actionIntent = new Intent(getBaseContext(), MyBroadcastSender.class);
actionIntent.putExtra("id", m);
Log.d(getClass().getSimpleName(), "Notification Id is : " + m);

然后,您可以检查idid1id2中有哪些值。别忘了使用从m得到的相同Id调用.notify()

您还可以创建getRandomNotificationId()getLastGeneratedNotificationId()方法。每当您生成一个Id时,请将其存储在public static整数变量中,以便您可以在整个类中访问它。

问题可能是您在初始化m之前就从NotificationARBroadcastReceiver中访问它。所以,它肯定会是0。而且,您提到了println错误,您是否在使用System.out.println()

修改前::

正如您新编辑的那样,在启动通知之前尝试关闭通知:

m = (...);

// some code here

mNotifyMgr.cancel(m);
mNotifyMgr.notify(m, notification);

看看您的问题是否得到解决。


这确实阻止了多次播放通知声音和多次在状态栏中出现通知,但仍然打印出:D/m: 1481727352 D/m: 1481727352 D/m: 1481727352 D/m: 1481727352 D/id: 1481727352 D/id1: 1481727352并未能从状态栏中删除通知。 - Hammad Nasir
不,兄弟...有些混淆了...int m = (new Random()).nextInt(10000);是在NotificationARBroadcastReceiver.java文件中,那里构建了通知,而我必须在MyBroadcastReceiver.java中使用相同的ID(正如您在GitHub示例中所描述的那样,它是一个内部类),以便在单击操作按钮时删除此通知。 - Hammad Nasir
就像SiliconEagle所说的那样,在创建通知时生成notificationId(m)。并且在NotificationARBroadcastReceiver.recieve()内部调用getNotificationNewRequestService() - rupinderjeet
问题是如何?getNotificationNewRequestService()在另一个文件中,而NotificationARBroadcastReceiver.java本身就是一个单独的文件!! - Hammad Nasir
我可以获取你的项目,或创建一个最小示例项目吗? - rupinderjeet
什么最适合你? - Hammad Nasir

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接