首页 文章

NotificationListenerService无法在Android Oreo上启动

提问于
浏览
2

我有一个使用 NotificationListenerService 的应用程序 . 它完全适用于低于Android Oreo的apis,但特别是在Android Oreo,当用户 restart 应用程序(它在用户第一次授予权限的时刻工作)时,系统似乎无法启动服务,即使已经授予了权限 . 我在StackOverflow上找不到针对此问题的任何解决方案 .


AndroidManifest

<service android:name=".Services.MyCustomNotificationListener"
android:label="MyAppName"
android:exported="true"
android:permission="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE">
<intent-filter>
    <action android:name="android.service.notification.NotificationListenerService" />
</intent-filter>

1 回答

  • 1

    好的,这不是很好的测试 . 我只是想把它扔到那里,希望能帮助其他人解决同样的问题 . 您似乎必须使用onListenerConnected和getActiveNotification()来使OREO设备接收通知 . 这是我的代码:

    public class ListenForNotificationsService extends NotificationListenerService {
    
        private String TAG = this.getClass().getSimpleName();
    
        @Override
        @TargetApi(Build.VERSION_CODES.N)
        public void onListenerConnected() {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                getActiveNotifications();
            }
            Log.d(TAG, "Listener connected");
        }
    
        @Override
        public void onNotificationPosted(StatusBarNotification sbn) {
    
            Log.d(TAG, "Notification received");
        }
    
        @Override
        public void onNotificationRemoved(StatusBarNotification sbn) {
    
            if (sbn.getPackageName() != null) {
    
                Log.d(TAG, "Notification removed:" + sbn.getPackageName() + ":" + sbn.getId());
            }
        }
    
        @Override
        @TargetApi(Build.VERSION_CODES.N)
        public void onListenerDisconnected() {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                // Notification listener disconnected - requesting rebind
                requestRebind(new ComponentName(this, NotificationListenerService.class));
            }
        }
    }
    

    请注意,我不知道onListenerDisconnected()是否正确甚至是必要的,因此请谨慎使用 . 另一个想法是,由于OREO中的DEEP SLEEP变化,可能还需要处理其他事情 . YMMV,这只是浪费了我很多时间,所以希望它会帮助别人 .

相关问题