android - 如何在 Android 上启动 NotificationListenerService

标签 android notifications android-service android-service-binding notification-listener

我想使用 NotificationListenerService 在 Android 手机上访问通知。我查了很多教程,但我找不到他们在哪里调用该服务。

我应该在 MainActivity 上使用 bindService 还是 startService? Intent 应该是什么样的?有人可以告诉我这个的语法吗?

查看我正在研究的服务实现之一:

public class NLService extends NotificationListenerService {

Context context;

@Override
public void onCreate() {

    super.onCreate();
    context = getApplicationContext();


}


@Override
public void onNotificationPosted(StatusBarNotification sbn) {
    String pack = sbn.getPackageName();
    String ticker ="";
    if(sbn.getNotification().tickerText !=null) {
        ticker = sbn.getNotification().tickerText.toString();
    }
    Bundle 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 msgrcv = new Intent("Msg");
    msgrcv.putExtra("package", pack);
    msgrcv.putExtra("ticker", ticker);
    msgrcv.putExtra("title", title);
    msgrcv.putExtra("text", text);
    if(id != null) {
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        //id.compress(Bitmap.CompressFormat.PNG, 100, stream);
        byte[] byteArray = stream.toByteArray();
        msgrcv.putExtra("icon",byteArray);
    }
    LocalBroadcastManager.getInstance(context).sendBroadcast(msgrcv);

}
@Override

public void onNotificationRemoved(StatusBarNotification sbn) {
    Log.i("Msg","Notification Removed");

}

最佳答案

对于监听传入的通知,他们不需要显式启动它。首先使用以下权限在 list 中定义您的服务 -

android.permission.BIND_NOTIFICATION_LISTENER_SERVICE

 <service android:name=".MyNotificationListener"
      android:permission="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE">
     <intent-filter>
         <action android:name="android.service.notification.NotificationListenerService" />
     </intent-filter>
 </service>

另一件需要注意的事情是,您必须使用以下 Intent 授予权限 -

Intent intent=new Intent("android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS");

或手动授予通知访问权限。

关于android - 如何在 Android 上启动 NotificationListenerService,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42451538/

相关文章:

Android JWT 刷新 token 流程

android - 使用 Galaxy Nexus 进行 Eclipse 调试

iphone - iPhone 应用程序中基于计时器的提醒

ios - 是否可以在给定时间自动运行启动应用程序(在后台)?

Android:实现LocationManager的最佳实践

android - android中后退键和home键的区别

android - java.lang.UnsatisfiedLinkError : dalvik. system.PathClassLoader[DexPathList.....]找不到 "libdetection_based_tracker.so"

android - 在调用方法之前绑定(bind)服务

android - gcm.notification.e=1 在 Android 上的推送通知负载中代表什么?

android - 如果不希望操作被来电、AsyncTask 或服务停止,我应该使用什么?