点击通知按钮时关闭状态栏

6

如何在通知按钮点击后关闭状态栏?

我试过这个方法,但是我遇到了一个异常:

java.lang.NoSuchMethodException: collapse []
   at java.lang.Class.getConstructorOrMethod(Class.java:460)
   at java.lang.Class.getMethod(Class.java:915)
   ...

我的代码:

NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
    .setSmallIcon(R.drawable.icon)
    .setContentTitle("Sync Failed")
    .setContentText("Lorem ipsum dolor sit amet")
    .setStyle(new NotificationCompat.BigTextStyle().bigText("Lorem ipsum dolor sit amet"))
    .addAction(R.drawable.change, "Change Pass", pChangePass)
    .addAction(R.drawable.remove, "Ignore", pIgnore)
    .setAutoCancel(false);
mNotificationManager.notify(accountUnique, builder.build());

在NotificationIntent类中

@Override
public void onReceive(Context context, Intent intent) {
    int notificationID = intent.getExtras().getInt("NOT_ID");
    this.callbackContext = StatusBarNotification.getCallback();
    this.mNotificationManager = StatusBarNotification.getNotificationManager();

    this.mNotificationManager.cancel(notificationID);
    this.callbackContext.success(returnJSON(intent));
}
2个回答

36
以下解决方案应该更加简单,没有使用任何非公共API:
Intent it = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
context.sendBroadcast(it); 

1
你能告诉我在哪里使用它吗?是在onReceive还是action intent中? - Ajeet
非常好用!谢谢。只需在onRecieve中加入2行代码即可。 - franco phong
1
在最新的Android API 31+中,需要使用android.permission.BROADCAST_CLOSE_SYSTEM_DIALOGS权限,由于这是系统应用程序权限,我们无法使用此方法。 - Arul

2

好的,我解决了它。

private int currentApiVersion = android.os.Build.VERSION.SDK_INT;
...

Object sbservice = context.getSystemService("statusbar");
try {
    Class<?> statusbarManager = Class.forName("android.app.StatusBarManager");
    if (currentApiVersion <= 16) {
        Method collapse = statusbarManager.getMethod("collapse");
        collapse.invoke(sbservice);
    } else {
        Method collapse2 = statusbarManager.getMethod("collapsePanels");
        collapse2.invoke(sbservice);
    }
} catch (Exception e) {
    e.printStackTrace();
}

5
你应该真的接受Sam Lu的评论 - 因为它使用了非公共API,所以你的解决方案可能会在任何下一个版本上停止工作。正如你所看到的,你已经不得不添加if api<=16 - 很快你可能需要添加if api<=19 - imbryk
同意上面的评论。Sam的答案更简单,不涉及版本号。 - Saik
自 API 31 开始,statusBarManager!!.getMethod("collapsePanels") 不再起作用,因为它们已将其隐藏。 - Arul

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