Android 监听系统中消息通知事件

0. 学习文章

参考了下面Blog 彻底没有任何多余的代码java

https://blog.csdn.net/wanghang1208/article/details/49905403android

原来百度卫士的通知栏收纳是相似这样的原理完成的,很不错.web

1.演示结果

数据源头
这里写图片描述app

监听到的logide

03-24 14:37:04.264 6155-6155/com.lava.noticeobser D/MyNotificationListenService: onNotificationRemoved
03-24 14:39:19.928 6155-6155/com.lava.noticeobser D/MyNotificationListenService: onNotificationPosted
03-24 14:39:19.928 6155-6155/com.lava.noticeobser I/MyNotificationListenService: notify msg: title=北方多地气温创新高,南方新一轮降雨来袭,详情→ ,when=1521873559186 ,contentTitle=升温幅度明显! ,contentText=北方多地气温创新高,南方新一轮降雨来袭,详情→ ,contentSubtext=
03-24 14:39:20.235 6155-6155/com.lava.noticeobser D/MyNotificationListenService: onNotificationPosted
03-24 14:39:20.235 6155-6155/com.lava.noticeobser I/MyNotificationListenService: notify msg: title=这些美食不管如何请在开春吃→ ,when=1521873560030 ,contentTitle=错过等一年! ,contentText=这些美食不管如何请在开春吃→ ,contentSubtext=
03-24 14:39:54.276 6155-6155/com.lava.noticeobser D/MyNotificationListenService: onNotificationPosted
03-24 14:39:54.276 6155-6155/com.lava.noticeobser I/MyNotificationListenService: notify msg: title=正在保存屏幕截图...  ,when=1521873594184 ,contentTitle=正在保存屏幕截图... ,contentText=正在保存屏幕截图。 ,contentSubtext=
03-24 14:39:55.156 6155-6155/com.lava.noticeobser D/MyNotificationListenService: onNotificationPosted
03-24 14:39:55.156 6155-6155/com.lava.noticeobser I/MyNotificationListenService: notify msg: title=正在保存屏幕截图...  ,when=1521873595096 ,contentTitle=已抓取屏幕截图。 ,contentText=点按便可查看您的屏幕截图。 ,contentSubtext=

2.源码

  1. MyNotificationListenService 负责监听消息
package com.lava.noticeobser;

import android.app.Notification;
import android.os.Build;
import android.os.Bundle;
import android.service.notification.NotificationListenerService;
import android.service.notification.StatusBarNotification;
import android.util.Log;

import java.lang.reflect.Field;

public class MyNotificationListenService extends NotificationListenerService {


    private static final String TAG = MyNotificationListenService.class.getSimpleName();

    @Override
    public void onNotificationPosted(StatusBarNotification sbn) {
        super.onNotificationPosted(sbn);
        Log.d(TAG, "onNotificationPosted");

        Notification n = sbn.getNotification();
        if (n == null) {
            return;
        }
        // 标题和时间
        String title = "";
        if (n.tickerText != null) {
            title = n.tickerText.toString();
        }
        long when = n.when;
        // 其它的信息存在一个bundle中,此bundle在android4.3及以前是私有的,须要经过反射来获取;android4.3以后能够直接获取
        Bundle bundle = null;
        if (Build.VERSION.SDK_INT == Build.VERSION_CODES.JELLY_BEAN_MR2) {
            // android 4.3
            try {
                Field field = Notification.class.getDeclaredField("extras");
                bundle = (Bundle) field.get(n);
            } catch (NoSuchFieldException e) {
                e.printStackTrace();
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        } else if (Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN_MR2) {
            // android 4.3以后
            bundle = n.extras;
        }
        // 内容标题、内容、副内容
        String contentTitle = bundle.getString(Notification.EXTRA_TITLE);
        if (contentTitle == null) {
            contentTitle = "";
        }
        String contentText = bundle.getString(Notification.EXTRA_TEXT);
        if (contentText == null) {
            contentText = "";
        }
        String contentSubtext = bundle.getString(Notification.EXTRA_SUB_TEXT);
        if (contentSubtext == null) {
            contentSubtext = "";
        }

        Log.i(TAG, "notify msg: title=" + title + " ,when=" + when
                + " ,contentTitle=" + contentTitle + " ,contentText="
                + contentText + " ,contentSubtext=" + contentSubtext);
    }

    @Override
    public void onNotificationRemoved(StatusBarNotification sbn) {
        super.onNotificationRemoved(sbn);
        Log.d(TAG, "onNotificationRemoved");
    }
}
  1. Mainfest.xml 给 MyNotificationListenService 打辅助
<service  android:name=".MyNotificationListenService" android:label="mynotifyservice" android:permission="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE" >
            <intent-filter>
                <action android:name="android.service.notification.NotificationListenerService" />
            </intent-filter>
        </service>
  1. 开启服务
package com.lava.noticeobser;

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        startNotificationListenService();
    }

    // 发送通知
    public void sendNotice(View view) {
        NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        Notification n;
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
            // android 3.0以前
            n = new Notification(R.mipmap.ic_launcher, "title",
                    System.currentTimeMillis());
        } else {
            // android 3.0以后
            n = new Notification.Builder(MainActivity.this)
                    .setSmallIcon(R.mipmap.ic_launcher).setTicker("title")
                    .setContentTitle("content title")
                    .setContentText("content text").setSubText("sub text")
                    .setWhen(System.currentTimeMillis()).build();
        }
        manager.notify(0, n);
    }

    // 跳转服务通知的权限界面
    public void settingsNotice(View view) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
            Intent intent = new Intent(
                    "android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS");
            startActivity(intent);
        } else {
            Toast.makeText(MainActivity.this, "手机的系统不支持此功能", Toast.LENGTH_SHORT)
                    .show();
        }
    }

    // 启动监听消息通知服务
    private void startNotificationListenService() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
            Intent intent = new Intent(MainActivity.this,
                    MyNotificationListenService.class);
            startService(intent);
        } else {
            Toast.makeText(MainActivity.this, "手机的系统不支持此功能", Toast.LENGTH_SHORT)
                    .show();
        }
    }
}
  1. 简单粗暴的布局
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context="com.lava.noticeobser.MainActivity" android:orientation="vertical">

    <Button  android:onClick="sendNotice" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="发通知" />

    <Button  android:onClick="settingsNotice" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="开启监听权限" />
</LinearLayout>