Почему служба прослушивания уведомлений не запускается? - PullRequest
0 голосов
/ 22 октября 2018

Я пытаюсь реализовать NotificationListenerService в Android, но он не запускается.

MyNotificationService

public class MyNotificationService extends NotificationListenerService {

    private static final String TAG = "MyNotificationService";

    private boolean mConnected = false;

    @Override
    public ComponentName startService(Intent service) {
        Log.d(TAG, "Starting Notification service");
        return super.startService(service);
    }

    @Override
    public void onListenerConnected() {
        super.onListenerConnected();
        Log.d(TAG, "Listener connected");
        mConnected = true;
    }

    @Override
    public void onListenerDisconnected() {
        super.onListenerDisconnected();
        Log.d(TAG, "Listener disconnected");
        mConnected = false;
    }

    @Override
    public void onNotificationPosted(StatusBarNotification sbn) {
        super.onNotificationPosted(sbn);
        Log.d(TAG, "Listener notification posted mConnected=" + mConnected);
    }

    @Override
    public void onNotificationRemoved(StatusBarNotification sbn) {
        super.onNotificationRemoved(sbn);
        Log.d(TAG, "Listener notification posted mConnected=" + mConnected);
    }
}

MainActivity

public class MainActivity extends AppCompatActivity {

    private static final String CHANNEL_ID = "mychannel";
    private static final String TAG = "NotificationService:MainActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Log.d(TAG, "on create");
        createNotificationChannel();

        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this, CHANNEL_ID)
                .setSmallIcon(R.id.icon)
                .setContentTitle("contenttitle")
                .setContentText("contenttext")
                .setPriority(NotificationCompat.PRIORITY_DEFAULT)
                .setAutoCancel(true);
        NotificationManager notificationManager = getSystemService(NotificationManager.class);
        notificationManager.notify(1001, mBuilder.build());

        registerReceiver(new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                Log.d(TAG, "received " + intent.getAction());
                Toast.makeText(context, intent.getAction(), Toast.LENGTH_LONG).show();
            }
        }, new IntentFilter("android.service.notification.NotificationListenerService"));
    }

    private void createNotificationChannel() {
        NotificationChannel channel = new NotificationChannel(CHANNEL_ID, "mychannelname", NotificationManager.IMPORTANCE_DEFAULT);
        channel.setDescription("mychanneldescription");
        NotificationManager notificationManager = getSystemService(NotificationManager.class);
        notificationManager.createNotificationChannel(channel);
    }
}

AndroidManifest

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.fxnq76.notificationservice">

    <application
        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">
        <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=".MyNotificationService"
            android:label="MyNotificationServiceLabel"
            android:permission="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE">
            <intent-filter>
                <action android:name="android.service.notification.NotificationListenerService" />
            </intent-filter>
        </service>
    </application>

</manifest>

Единственный журнал, который печатает, это при создании.Кажется, что намерение даже не отправляется.Как вы можете видеть, я пытаюсь получить и напечатать его в MainActivity, но это утверждение никогда не печатается.

Я пытался вручную отправить намерение с помощью adb shell am start -a "android.service.notification.NotificationListenerService", но я получаю

Запуск: Intent {act = android.service.notification.NotificationListenerService} Ошибка: действие не запущено, не удается разрешить Intent {act = android.service.notification.NotificationListenerService flg = 0x10000000}

Я прочитал, что пользователю необходимо вручную включить разрешение на уведомления, но когда я захожу в приложение настроек, оно не запрашивает никаких разрешений, связанных с уведомлением.Я попытался добавить <uses-permission android:name="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE" /> в мой манифест, но это не имеет значения.

Как мне запустить службу прослушивания уведомлений?

...