受欢迎的博客标签

Android|Android Studio|安卓8.0系列(2):读取通知栏消息

Published

一、Notificaiton状态通知栏的功能作用 1.显示接收到短消息、即使消息等信息 (如QQ、微信、新浪、短信) 2.显示客户端的推送消息(如有新版本发布,广告,推荐新闻等) 3.显示正在进行的事物(例如:后台运行的程序)(如音乐播放器、版本更新时候的下载进度等) 4. 使用场景:NotificationListenerService 的使用范围挺广的,比如,抢红包,智能手表同步通知,通知栏去广告工具 二、客户端获取消息推送原理 消息推送有两种,一种是客户端定时直接到服务器搜索消息,如果发现有新的消息,就获取消息下来;另一种是服务器向客户端发送消息,也就是当有信息消息时,服务器端就会向客户端发送消息。   三、Android 8.0系统通知渠道的理解 Android 8.0系统开始,Google引入了通知渠道这个概念。举个具体的例子,对于支付宝App,我希望可以即时收到支付宝的收款信息,因为我不想错过任何一笔收益,但是我又不想收到支付宝给我推荐的周围美食。这种情况,支付宝就可以创建两种通知渠道,一个收支,一个推荐,而我作为用户对推荐类的通知不感兴趣,那么我就可以直接将推荐通知渠道关闭,这样既不影响我关心的通知,又不会让那些我不关心的通知来打扰我了。   四、开发步骤 step 1:准备android8.0的开发环境。 需修改minSdkVersion,targetSdkVersion api级别到26以上 打开app/build.gradle文件检查一下,确保targetSdkVersion已经指定到了26或者更高,如下所示: 打开app/build.gradle文件检查一下,确保targetSdkVersion已经指定到了26或者更高,确保minSdkVersion 已经指定到了26,如下所示: apply plugin: 'com.android.application' android { compileSdkVersion 26 defaultConfig { applicationId "com.example.notificationtest" minSdkVersion 26 targetSdkVersion 26 versionCode 1 versionName "1.0" testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" } } step 2:继承实现NotificationListenerService   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()); } } step 3: 配置Manifest 注册服务首先需要在AndroidManifest.xml对service进行注册。 step 4:向手机用户申请监听权限授权   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中关于内部存储的一些重要函数 https://blog.csdn.net/hudashi/article/details/8037076 华为手机打开日志输出的几种方法 https://blog.csdn.net/quantum7/article/details/79824640 完美的适配Android8.0未知来源应用安装权限方案 https://blog.csdn.net/changmu175/article/details/78906829 NotificationListenerService 的那些事儿 https://www.jianshu.com/p/981e7de2c7be NotificationListenerService不能监听到通知 http://www.cnblogs.com/dongweiq/p/5997210.html https://www.jb51.net/article/102993.htm https://blog.csdn.net/q1113225201/article/details/72630134    .