如何启动NotificationListenerService?

时间:2016-06-18 18:13:06

标签: java android android-service

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

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()startService(new Intent(context, NotificationListener.class));

中启动了该服务

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

1 个答案:

答案 0 :(得分:-1)

请看一下正确使用NotificationListenerService的一个很好的例子:

https://github.com/kpbird/NotificationListenerService-Example

在那里,您可以找到问题的答案:)