欢迎来到代码驿站!

Android代码

当前位置:首页 > 移动开发 > Android代码

android使用NotificationListenerService监听通知栏消息

时间:2021-05-07 10:49:28|栏目:Android代码|点击:

NotificationListenerService是通过系统调起的服务,在应用发起通知时,系统会将通知的应用,动作和信息回调给NotificationListenerService。但使用之前需要引导用户进行授权。使用NotificationListenerService一般需要下面三个步骤。

注册服务

首先需要在AndroidManifest.xml对service进行注册。

<service
  android:name=".NotificationCollectorService"
  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>

继承实现NotificationListenerService

自己实现一个继承NotificationListenerService的service,在onNotificationPosted中完成自己需要的操作。

public class NotificationCollectorService extends NotificationListenerService {
  @Override
  public void onNotificationPosted(StatusBarNotification sbn) {
    Log.i("xiaolong", "open" + "-----" + sbn.getPackageName());
    Log.i("xiaolong", "open" + "------" + sbn.getNotification().tickerText);
    Log.i("xiaolong", "open" + "-----" + sbn.getNotification().extras.get("android.title"));
    Log.i("xiaolong", "open" + "-----" + sbn.getNotification().extras.get("android.text"));
  }

  @Override
  public void onNotificationRemoved(StatusBarNotification sbn) {
    Log.i("xiaolong", "remove" + "-----" + sbn.getPackageName());

  }
}

引导用户进行授权

由于此服务需要用户手动进行授权,所以使用前需要对用户进行引导设置。

public class MainActivity extends AppCompatActivity {

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    String string = Settings.Secure.getString(getContentResolver(),
        "enabled_notification_listeners");
    if (!string.contains(NotificationCollectorService.class.getName())) {
      startActivity(new Intent(
          "android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS"));
    }
  }
}

用户授权后就可以对通知栏的所有信息进行监听了。

上一篇:Android自定义ViewGroup打造各种风格的SlidingMenu

栏    目:Android代码

下一篇:Android中WebView加载的网页被放大的解决办法

本文标题:android使用NotificationListenerService监听通知栏消息

本文地址:http://www.codeinn.net/misctech/116579.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有