Android:重新启动应用程序后,NotificationListenerService无法正常工作

时间:2019-09-11 17:32:55

标签: android android-notifications

我正在尝试读取通知,但是一旦我杀死并重新启动应用程序,NotificationListenerService就不会读取通知。

在启用断点时,我看到断点仅在onNotificationPosted(第一次启动)中出现一次。重新启动应用程序后,NotificationListenerService不起作用

我正在使用android pie

有什么解决办法吗?

NotificationListenerExampleService

public class NotificationListenerExampleService extends NotificationListenerService {

@Override
    public IBinder onBind(Intent intent) {
        return super.onBind(intent);
    }

    @Override
    public void onNotificationPosted(StatusBarNotification sbn) {
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
            if ((sbn.getNotification().flags & Notification.FLAG_GROUP_SUMMARY) != 0) {
                //Ignore the notification
                return;
            }
            int notificationCode = matchNotificationCode(sbn);

            if (notificationCode != InterceptedNotificationCode.OTHER_NOTIFICATIONS_CODE) {
                String pack = sbn.getPackageName();
                String ticker = "";
                if (sbn.getNotification().tickerText != null) {
                    ticker = sbn.getNotification().tickerText.toString();
                }
                Bundle extras = null;

                extras = sbn.getNotification().extras;

                String title = extras.getString("android.title");
                String text = extras.getCharSequence("android.text").toString();
                int id1 = extras.getInt(Notification.EXTRA_SMALL_ICON);
                Bitmap id = sbn.getNotification().largeIcon;


                Log.i("Package", pack);
                Log.i("Ticker", ticker);
                Log.i("Title", title);
                Log.i("Text", text);


                Intent intent = new Intent("com.github.chagall.notificationlistenerexample");
                intent.putExtra("Notification Code", notificationCode);
                intent.putExtra("package", pack);
                intent.putExtra("ticker", ticker);
                intent.putExtra("title", title);
                intent.putExtra("text", text);
                if (id != null) {
                    ByteArrayOutputStream stream = new ByteArrayOutputStream();
                    id.compress(Bitmap.CompressFormat.PNG, 100, stream);
                    byte[] byteArray = stream.toByteArray();
                    intent.putExtra("icon", byteArray);
                }
                sendBroadcast(intent);
            }
        }
    }

AndroidManifest.xml

<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>

0 个答案:

没有答案
相关问题