我正在创建一个App来访问一些Notifications,下面是我的AndroidManifest.xml文件。我安装了我的应用程序但是当我转到设备的通知访问设置时,我看不到我的应用程序列在那里,任何人都可以帮我这个
<application
android:name=".MyApplication"
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme"
tools:ignore="GoogleAppIndexingWarning">
<service
android:name="com.example.myapp.otp.MyService"
android:label="@string/service_name"
android:permission="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE">
<intent-filter>
<action android:name="android.service.
notification.NotificationListenerService" />
</intent-filter>
</service>
</application>
这是MyService.class:
public class MyService extends NotificationListenerService {
@Override
public void onNotificationPosted(StatusBarNotification sbn) {
Notification mNotification = sbn.getNotification();
if (mNotification != null) {
Bundle extras = mNotification.extras;
Intent intent = new Intent(MainActivity.INTENT_ACTION_NOTIFICATION);
intent.putExtras(extras);
sendBroadcast(intent);
}
}
@Override
public void onNotificationRemoved(StatusBarNotification sbn) {
}
}
如果您使用的是22以上的API,首先获得运行时权限
if (Build.VERSION.SDK_INT > 22) {
requestPermissions(new String[]{Manifest.permission
.BIND_NOTIFICATION_LISTENER_SERVICE}, 1001);
}
您将获得onRequestPermissionsResult
的回应以获得上述许可
然后在您的活动中询问用户是否允许您的应用通过获取通知侦听器组件来访问通知
Set<String> listnerSet = NotificationManagerCompat.getEnabledListenerPackages(this);
boolean haveAccess = false;
for (String sd : listnerSet) {
if (sd.equals("your -- package -- name")) {
haveAccess = true;
}
}
if (!haveAccess) {
startActivity(new Intent(Settings.ACTION_NOTIFICATION_LISTENER_SETTINGS));
}