【发布时间】:2019-01-06 07:38:51
【问题描述】:
背景
我发现了一个名为NCleaner 的应用程序,它以某种方式隐藏了提醒通知,甚至包括正在进行的通知(由前台服务使用)。
我想知道这样的事情是如何工作的。
问题
没有太多关于如何控制其他应用通知的信息。仅限当前应用,由于某种原因,我未能取消正在进行的通知,但我成功取消了正常通知。
我发现了什么
我发现this sample 展示了如何监控通知。在搜索有关NotificationListenerService 的文档后,我还找到了如何取消其他应用程序的特定通知。
但是,它不适用于持续通知。
为了测试正常通知,我只是通过我的电脑给自己发了一封电子邮件或在 PushBullet 应用程序上写了一些东西。
为了测试持续通知,我安装并运行了我的业余时间应用程序 (here),它在应用程序的开头显示持续通知,从 Android O 开始。事实上,它甚至可以隐藏操作系统、USB 连接和调试的通知(只需通过 USB 将设备连接到 PC)...
这是我根据示例制作的代码,用于取消收到的所有通知:
NotificationListenerExampleService.kt
class NotificationListenerExampleService : NotificationListenerService() {
override fun onNotificationPosted(sbn: StatusBarNotification) {
Log.d("AppLog", "sbn:" + sbn.toString())
cancelNotification(sbn.key)
}
override fun onListenerConnected() {
super.onListenerConnected()
Log.d("AppLog", "onListenerConnected")
}
override fun onNotificationRemoved(sbn: StatusBarNotification) {}
}
清单:
<application
android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:supportsRtl="true" android:theme="@style/AppTheme"
tools:ignore="AllowBackup,GoogleAppIndexingWarning">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<service
android:name=".NotificationListenerExampleService" android:label="@string/service_label" android:permission="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE">
<intent-filter>
<action android:name="android.service.notification.NotificationListenerService"/>
</intent-filter>
</service>
</application>
MainActivity.kt
class MainActivity : AppCompatActivity() {
private val isNotificationServiceEnabled: Boolean
get() {
val pkgName = packageName
val flat = Settings.Secure.getString(contentResolver, "enabled_notification_listeners"")
if (!TextUtils.isEmpty(flat)) {
val names = flat.split(":".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
for (i in names.indices) {
val cn = ComponentName.unflattenFromString(names[i])
if (cn != null) {
if (TextUtils.equals(pkgName, cn.packageName)) {
return true
}
}
}
}
return false
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
if (!isNotificationServiceEnabled) {
startActivity(Intent("android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS"))
}
}
}
问题
- 为什么我的代码无法删除正在进行的通知?
- 我找到的这个app怎么能做到?它有什么作用?
- 这个 API 在通知方面提供了多少?查看文档,它似乎可以做很多事情:阅读通知,关闭它们,获取有关它们的各种信息,......但我找不到其他一些功能:是否可以修改通知?改变它的优先级?为了避免成为提醒通知而只是在通知抽屉中?是否可以触发通知的动作?
【问题讨论】:
-
也许它会暂停一个无法清除或正在进行的通知? developer.android.com/reference/android/service/notification/…
-
可以触发通知动作吗?可能可以,因为它可以通过
StatusBarNotification访问Notification,并且可以从Notification获取PendingIntents -
@Ufkoku 似乎运作良好。为什么不把它作为答案让我接受呢?另外,你知道这个的替代品吗,因为它需要 Android O ?
-
另外,你能回答其他问题吗?
-
我打算明天或周一写一个完整的答案,如果没有人会在我之前完成)
标签: android notifications foreground-service heads-up-notifications