Android監聽系統通知

1. API簡介

Android在4.3的版本中(即API 18)加入了NotificationListenerService,根據SDK的描述(AndroidDeveloper)能夠知道,當系統收到新的通知或者通知被刪除時,會觸發NotificationListenerService的回調方法。同時在Android 4.4 中新增了Notification.extras 字段,也就是說能夠繼承NotificationListenerService獲取系統通知具體信息。android

而後通常會重寫下面這三個方法:web

onNotificationPosted(StatusBarNotification sbn) :當有新通知到來時會回調;
onNotificationRemoved(StatusBarNotification sbn) :當有通知移除時會回調;
onListenerConnected() :當 NotificationListenerService 是可用的而且和通知管理器鏈接成功時回調。

2. 系統監聽功能實現

2.1 新建NotificationMonitor類繼承自NotificationListenerService,這是監聽系統消息的核心服務類

public class NotificationMonitor extends NotificationListenerService {
        @Override
        public void onNotificationPosted(StatusBarNotification sbn) {
                Bundle extras = sbn.getNotification().extras;
        	    // 獲取接收消息APP的包名
        		String notificationPkg = sbn.getPackageName();
       			 // 獲取接收消息的擡頭
        		String notificationTitle = extras.getString(Notification.EXTRA_TITLE);
        		// 獲取接收消息的內容
        		String notificationText = extras.getString(Notification.EXTRA_TEXT);
        		Log.i("NotificationMonitor", "Notification posted " + notificationTitle + " & " + notificationText);
        }
 
        @Override
        public void onNotificationRemoved(StatusBarNotification sbn) {
                // TODO Auto-generated method stub
        		Bundle extras = sbn.getNotification().extras;
        		// 獲取接收消息APP的包名
        		String notificationPkg = sbn.getPackageName();
        		// 獲取接收消息的擡頭
        		String notificationTitle = extras.getString(Notification.EXTRA_TITLE);
        		// 獲取接收消息的內容
        		String notificationText = extras.getString(Notification.EXTRA_TEXT);
        		Log.i("NotificationMonitor", "Notification removed " + notificationTitle + " & " + notificationText);
        }
}

2.2 NotificationMonitor服務類須要在AndroidManifest.xml中註冊

<service android:name=".NotificationMonitor"
          android:label="@string/service_name"
          android:permission="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE">
     <intent-filter>
         <action android:name="android.service.notification.NotificationListenerService" />
     </intent-filter>
 </service>

2.3 新建程序的主入口MainActivity類,並在onCreate方法中開啓監聽服務NotificationMonitor

Intent intent = new Intent(this, NotificationMonitor.class);
 startService(intent);

同時須要在AndroidManifest.xml中註冊MainActivityapp

<activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

2.4 因爲系統消息監聽權限須要手動設置,這裏添加一個代碼,打開設置頁面,方便開啓系統消息監聽權限

public void openNotificationListenSettings() {
    try {
        Intent intent;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP_MR1) {
            intent = new Intent(Settings.ACTION_NOTIFICATION_LISTENER_SETTINGS);
        } else {
            intent = new Intent("android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS");
        }
        startActivity(intent);
    } catch (Exception e) {
        e.printStackTrace();
    }
}
在Mainactivity的onCreate方法中調用openNotificationListenSettings()便可

2.5 監聽到系統消息之後能夠經過發廣播的方式與MainActivity通訊,將監聽消息傳遞到前臺頁面,並顯示在列表中

public class MonitorBroadcastReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        String title = intent.getStringExtra("notificationTitle");
        String text = intent.getStringExtra("notificationText");
    }
}

同時須要在AndroidManifest.xml中註冊MonitorBroadcastReceiveride

<receiver android:name="com.example.receiver.MonitorBroadcastReceiver">
            <intent-filter>
                 <action android:name="com.example.BROADCAST"/>
            </intent-filter>
</receiver>

最後在NotificationMonitor中接收到系統消息的地方發送廣播就好了svg

public void onReceive(String notificationTitle, String notificationText) {
		Intent intent = new Intent("com.example.BROADCAST");
		intent.putExtra("notificationTitle", notificationTitle);
		intent.putExtra("notificationText",notificationText);
		sendBroadcast(intent);
}