点击通知按钮后如何关闭状态栏/通知面板?

36

我浏览了Stackoverflow并发现这个问题已经被问过了,但我没有找到任何解决方案。

我有一个带有两个按钮的自定义通知。我想在按下通知上的按钮后关闭状态栏面板,但不知道如何实现。如果我按通知本身(即contentIntent),则面板会关闭,这也是我对我的按钮所希望的。

这是我的通知代码:

Notification notification = new Notification(R.drawable.icon, "Service running", System.currentTimeMillis());
notification.flags |= Notification.FLAG_ONGOING_EVENT;
notification.contentIntent = openIntent;
RemoteViews contentView = new RemoteViews(getPackageName(), R.layout.notification_layout);


contentView.setOnClickPendingIntent(R.id.button1, stopIntent);
contentView.setOnClickPendingIntent(R.id.button2, addIntent);

notification.contentView = contentView;

notificationManager.notify(NOTIFICATION_ID, notification);

按钮从API Level 11开始支持。您在我现在已删除的答案中的评论中指出这是您的“minSdkVersion”,因此您应该没问题,尽管我不知道如何关闭抽屉。对于我的错误表示歉意 - 我忘记了他们正式开始支持这一点。 - CommonsWare
可能我应该提前说明一下,我的minSdkVersion = 11 ;-) - Toni Kanoni
3个回答

121

使用以下两行代码折叠通知栏。

Intent it = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
context.sendBroadcast(it);

2
这是正确的答案,因为此代码不使用私有API即可运行。 - CeccoCQ
你节省了我的时间。谢谢。 - BSKANIA
1
请提供原始文本以便进行翻译。 - Pelanes
这再简单不过了,绝对是正确的做法。 - Thunderstick

3

好的,我找到了解决方案。它不是公共API,但它有效(目前):

Object sbservice = c.getSystemService( "statusbar" );
                    Class<?> statusbarManager = Class.forName( "android.app.StatusBarManager" );
                    Method hidesb = statusbarManager.getMethod( "collapse" );
                    hidesb.invoke( sbservice );

为了使此功能正常工作

<uses-permission android:name="android.permission.EXPAND_STATUS_BAR"/>

需要

的内容


@iDroidExplorer:c 是上下文。正如我在问题中所要求的那样,这段代码能够关闭已展开的通知栏面板。我在按下自定义通知按钮后使用该代码片段。 - Toni Kanoni

2

针对Android 11及以下版本:

获取权限:
<uses-permission android:name="android.permission.EXPAND_STATUS_BAR"/>

然后:

Object statusBarService = context.getSystemService("statusbar");
Class<?> statusBarManager = Class.forName("android.app.StatusBarManager");
Method collapse = statusBarManager.getMethod("collapse");
collapse.invoke( statusBarService );

针对Android 12及以上版本:

要么您的应用程序应该是系统应用程序, 然后使用上述相同的权限,该方法将起作用

对于第三方应用程序... 此功能不可用

/**
 * Collapse the notifications and settings panels.
 *
 * Starting in Android {@link Build.VERSION_CODES.S}, apps targeting SDK level {@link
 * Build.VERSION_CODES.S} or higher will need {@link android.Manifest.permission.STATUS_BAR}
 * permission to call this API.
 *
 * @hide
 */
@RequiresPermission(android.Manifest.permission.STATUS_BAR)
@UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, publicAlternatives = "This operation"
        + " is not allowed anymore, please see {@link android.content"
        + ".Intent#ACTION_CLOSE_SYSTEM_DIALOGS} for more details.")
@TestApi
public void collapsePanels() {
  ...
}

并使用Intent.ACTION_CLOSE_SYSTEM_DIALOGS

参考这里


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