android使用NotificationListenerService监听通知栏消息
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中通过Notification&NotificationManager实现消息通知
- Android编程实现google消息通知功能示例
- Android之开发消息通知栏
- Android消息通知栏的实现方法介绍
- Android自定义Notification添加点击事件
- Android中AlarmManager+Notification实现定时通知提醒功能
- Android 中Notification弹出通知实现代码
- Android编程使用Service实现Notification定时发送功能示例
- Android 通知使用权(NotificationListenerService)的使用
- Android消息通知Notification常用方法(发送消息和接收消息)
相关文章
Android ViewPager中显示图片与播放视频的填坑记录
这篇文章主要给介绍了关于Android ViewPager中显示图片与播放视频的一些填坑记录,文中通过示例代码介绍的非常详细,对各位Android开发者们具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧。2018-05-05VS Code开发React-Native及Flutter 开启无线局域网安卓真机调试问题
这篇文章主要介绍了VS Code开发React-Native,Flutter 开启无线局域网安卓真机调试,需要的朋友可以参考下2020-04-04Flutter 封装一个 Banner 轮播图效果的实例代码
这篇文章主要介绍了Flutter 封装一个 Banner 轮播图效果,本文通过实例代码给大家介绍的非常详细,具有一定的参考借鉴价值,需要的朋友可以参考下2019-07-07
最新评论