android使用NotificationListenerService監(jiān)聽通知欄消息
NotificationListenerService是通過系統(tǒng)調起的服務,在應用發(fā)起通知時,系統(tǒng)會將通知的應用,動作和信息回調給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"));
}
}
}
用戶授權后就可以對通知欄的所有信息進行監(jiān)聽了。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
- Android中通過Notification&NotificationManager實現消息通知
- Android編程實現google消息通知功能示例
- Android之開發(fā)消息通知欄
- Android消息通知欄的實現方法介紹
- Android自定義Notification添加點擊事件
- Android中AlarmManager+Notification實現定時通知提醒功能
- Android 中Notification彈出通知實現代碼
- Android編程使用Service實現Notification定時發(fā)送功能示例
- Android 通知使用權(NotificationListenerService)的使用
- Android消息通知Notification常用方法(發(fā)送消息和接收消息)
相關文章
Android中使用GridLayout網格布局來制作簡單的計算器App
這篇文章主要介紹了Android中使用GridLayout網格布局來制作簡單的計算器App的實例,GridLayout比表格布局TabelLayout更容易用來制作計算器這樣的多按鈕排列的界面,需要的朋友可以參考下2016-04-04

