android监听应用服务,android使用NotificationListenerService监听通知栏消息

NotificationListenerService是通过系统调起的服务,在应用发起通知时,系统会将通知的应用,动作和信息回调给NotificationListenerService。但使用之前需要引导用户进行授权。使用NotificationListenerService一般需要下面三个步骤。

注册服务

首先需要在AndroidManifest.xml对service进行注册。

android:name=".NotificationCollectorService"

android:label="@string/app_name"

android:permission="android.permission.BIND_NOTIFICATION_LISTENER_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"));

}

}

}

用户授权后就可以对通知栏的所有信息进行监听了。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值