监听通知栏中的消息

0、首先推荐一个具有此功能的App—快牙网传,在“我的“–“推送通知“里面使用到了监听通知栏中的消息。
在豌豆荚等应用商店搜索“快牙网传“,或立即下载 Apk,也可以扫码下载。
监听通知栏中的消息_第1张图片

进入正题:

1、android中的通知栏由NotificationManager管理,表示通知的类是Notification。
2、android4.3开始增加了抽象类NotificationListenerService,通过继承它可以监听到通知栏中通知的变化:post、delete,并可以获取到通知的信息。
3、使用步骤如下:
3.1 自定义一个类继承自NotificationListenerService,重写其中的两个方法:onNotificationPosted()、onNotificationRemoved()。

@SuppressLint("NewApi")
public class MyNotificationListenService extends NotificationListenerService {

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return super.onStartCommand(intent, flags, startId);
    }

    // 有新的通知
    @Override
    public void onNotificationPosted(StatusBarNotification sbn) {
        Log.e("wanghang", "get notify");
        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.e("wanghang", "notify msg: title=" + title + " ,when=" + when
                + " ,contentTitle=" + contentTitle + " ,contentText="
                + contentText + " ,contentSubtext=" + contentSubtext);
    }

    // 通知被删除了
    @Override
    public void onNotificationRemoved(StatusBarNotification sbn) {
        Log.e("wanghang", "delete notify");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }
}

3.2 注册这个服务




    

    
        
            
                

                
            
        

        
        
            
                
            
        
    


3.3 开启服务,设置权限,发送通知

public class MainActivity extends Activity implements OnClickListener {

    private Button notifyButton;
    private Button setAuthButton;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initView();
        // 开启服务
        startNotificationListenService();
    }

    private void initView() {
        notifyButton = (Button) findViewById(R.id.button_notify);
        notifyButton.setOnClickListener(this);
        setAuthButton = (Button) findViewById(R.id.button_setauth);
        setAuthButton.setOnClickListener(this);
    }

    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();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        case R.id.button_notify:
            showNotify();
            break;
        case R.id.button_setauth:
            setAuth();
            break;
        default:
            break;
        }
    }

    @SuppressLint("NewApi")
    @SuppressWarnings("deprecation")
    private void showNotify() {
        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.drawable.ic_launcher, "title",
                    System.currentTimeMillis());
        } else {
            // android 3.0之后
            n = new Notification.Builder(MainActivity.this)
                    .setSmallIcon(R.drawable.ic_launcher).setTicker("title")
                    .setContentTitle("content title")
                    .setContentText("content text").setSubText("sub text")
                    .setWhen(System.currentTimeMillis()).build();
        }
        manager.notify(0, n);
    }

    private void setAuth() {
        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();
        }
    }
}

3.4 简单的布局文件activity_main.xml



    

4、需要在android4.3及之后的手机上运行,并开启通知服务。
5、推荐一个具有此功能的App—快牙网传,在“我的“–“推送通知“里面使用到了监听通知栏中的消息。

在豌豆荚等应用商店搜索“快牙网传“,或立即下载 Apk,也可以扫码下载。
监听通知栏中的消息_第2张图片

你可能感兴趣的:(Android)