NotificationListenerService是通過系統(tǒng)調(diào)起的服務(wù),在應(yīng)用發(fā)起通知時,系統(tǒng)會將通知的應(yīng)用,動作和信息回調(diào)給NotificationListenerService。但使用之前需要引導(dǎo)用戶進(jìn)行授權(quán)。使用NotificationListenerService一般需要下面三個步驟。
注冊服務(wù)
首先需要在AndroidManifest.xml對service進(jìn)行注冊。
<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>
繼承實(shí)現(xiàn)NotificationListenerService
自己實(shí)現(xiàn)一個繼承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()); }}引導(dǎo)用戶進(jìn)行授權(quán)
由于此服務(wù)需要用戶手動進(jìn)行授權(quán),所以使用前需要對用戶進(jìn)行引導(dǎo)設(shè)置。
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")); } }}用戶授權(quán)后就可以對通知欄的所有信息進(jìn)行監(jiān)聽了。
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持武林網(wǎng)。
新聞熱點(diǎn)
疑難解答
圖片精選