Java 如何启动NotificationListenerService?

Java 如何启动NotificationListenerService?,java,android,android-service,Java,Android,Android Service,今天我开始为安卓系统写作。我想要一个简单的(我想)应用程序,它用指定的标题等待通知,然后做一些事情。我试过这个代码来服务 import android.app.NotificationManager; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.service.notification.NotificationListenerServ

今天我开始为安卓系统写作。我想要一个简单的(我想)应用程序,它用指定的标题等待通知,然后做一些事情。我试过这个代码来服务

import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.service.notification.NotificationListenerService;
import android.service.notification.StatusBarNotification;
import android.util.Log;
import android.support.v4.content.LocalBroadcastManager;
import android.widget.Toast;


public class NotificationListener extends NotificationListenerService {

Context context;
public int onStartCommand(Intent intent, int flags, int startId) {
    // Let it continue running until it is stopped.
    Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
    return START_STICKY;
}
@Override

public void onCreate() {
    Toast.makeText(this, "onCreate", Toast.LENGTH_LONG).show();
    super.onCreate();
    context = getApplicationContext();


}
@Override

public void onNotificationPosted(StatusBarNotification sbn) {


    String pack = sbn.getPackageName();
    Toast.makeText(this,"NOTIFICATION",Toast.LENGTH_SHORT).show();
    String text = "";
    String title = "";
    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
        Bundle extras = extras = sbn.getNotification().extras;
        text = extras.getCharSequence("android.text").toString();
        title = extras.getString("android.title");
    }

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

}

@Override
public void onNotificationRemoved(StatusBarNotification sbn) {
    Toast.makeText(this,"NOTIFICATION removed",Toast.LENGTH_SHORT).show();
    Log.i("Msg","Notification was removed");
}
}
然后将此添加到清单:

<service
            android:name=".NotificationListener"
            android:enabled="true"
            android:label="@string/app_name"
            android:permission="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE">
            <intent-filter>
                <action android:name="android.service.notification.NotificationListenerService" />
            </intent-filter>
        </service>

终于在MainActivity onCreate()中启动了服务(新意图(context,NotificationListener.class))


通知发布不起作用。似乎服务启动正确,因为显示了onStartCommand和onCreate的祝酒词。我在模拟器和真实设备上进行了尝试。我还允许在设置中访问通知。请帮忙,我在这上面浪费了5个小时。

请看一个正确使用NotificationListenerService的好例子:在那里你可以找到问题的答案:)