NotificationListenerService

NotificationListenerService

本文介绍了如何在Android上启动NotificationListenerService的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I would like to access notifications on a Android phone by using the NotificationListenerService. I checked lots of tutorials but I can't find where they call the service.

我应该在MainActivity上使用bindService还是startService?意向应如何显示?有人可以告诉我这个语法吗?

Should I use bindService or startService on MainActivity? How should the intents look like? Can someone show me the syntax of this?

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

Check out one of the service implementations I am studying:

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");

}

}

推荐答案

对于监听传入的通知,他们无需显式启动它.首先,在具有以下权限的清单中定义您的服务-

For listening incoming notifications, their is no need to start it explicitly . First define your service in manifest with the following permission -

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

要注意的另一件事是,您必须使用以下意图授予许可-

Another thing to take care is that you must grant the permission either by using the following intent -

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

或通过手动授予通知访问权限.

or by granting the notification access manually.

这篇关于如何在Android上启动NotificationListenerService的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-17 01:24