Android 通知监听服务、NotificationListenerService使用方式(详细步骤+源码

服务配置完成了,下面进行具体的打开服务操作。

三、打开通知服务监听


使用这个通知服务其实就是打开一个手机上应用的开关,效果上和打开蓝牙差不多,下面先写一个方法检查当前应用是否开启这个服务。方法代码如下:

/**

  • 是否启用通知监听服务

  • @return

*/

public boolean isNLServiceEnabled() {

Set packageNames = NotificationManagerCompat.getEnabledListenerPackages(this);

if (packageNames.contains(getPackageName())) {

return true;

}

return false;

}

这里还对应一个方法就是设置服务是否运行,如下:

/**

  • 切换通知监听器服务

  • @param enable

*/

public void toggleNotificationListenerService() {

PackageManager pm = getPackageManager();

pm.setComponentEnabledSetting(new ComponentName(getApplicationContext(), NotifyService.class),

PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP);

pm.setComponentEnabledSetting(new ComponentName(getApplicationContext(), NotifyService.class),

PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP);

}

现在方法有了需要一个地方去触发,通过按钮来进行,在activity_main.xml添加一个按钮。

<?xml version="1.0" encoding="utf-8"?>

<androidx.constraintlayout.widget.ConstraintLayout xmlns:android=“http://schemas.android.com/apk/res/android”

xmlns:app=“http://schemas.android.com/apk/res-auto”

xmlns:tools=“http://schemas.android.com/tools”

android:layout_width=“match_parent”

android:layout_height=“match_parent”

tools:context=“.MainActivity”>

<TextView

android:id=“@+id/textView”

android:layout_width=“wrap_content”

android:layout_height=“wrap_content”

android:text=“Hello World!”

app:layout_constraintBottom_toBottomOf=“parent”

app:layout_constraintLeft_toLeftOf=“parent”

app:layout_constraintRight_toRightOf=“parent”

app:layout_constraintTop_toTopOf=“parent” />

<Button

android:layout_width=“wrap_content”

android:layout_height=“wrap_content”

android:text=“请求权限”

android:onClick=“requestPermission”

app:layout_constraintBottom_toBottomOf=“parent”

app:layout_constraintEnd_toEndOf=“parent”

app:layout_constraintStart_toStartOf=“parent”

app:layout_constraintTop_toBottomOf=“@+id/textView” />

</androidx.constraintlayout.widget.ConstraintLayout>

在MainActivity中添加一个方法:

private static final int REQUEST_CODE = 9527;

/**

  • 请求权限

  • @param view

*/

public void requestPermission(View view) {

if (!isNLServiceEnabled()) {

startActivityForResult(new Intent(“android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS”), REQUEST_CODE);

} else {

showMsg(“通知服务已开启”);

toggleNotificationListenerService(true);

}

}

这个还有一个showMsg方法:

private void showMsg(String msg) {

Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();

}

然后是页面返回:

@Override

protected void onActivityResult(int requestCode, int resultCode, Intent data) {

super.onActivityResult(requestCode, resultCode, data);

if (requestCode == REQUEST_CODE) {

if (isNLServiceEnabled()) {

showMsg(“通知服务已开启”);

toggleNotificationListenerService(true);

} else {

showMsg(“通知服务未开启”);

toggleNotificationListenerService(false);

}

}

}

下面就可以先运行一下:

在这里插入图片描述

现在就可以测试数据,这里建议你找一个朋友给你发消息,保持电脑上没有登录微信和QQ,然后手机上的微信和QQ保持后台运行就可以了,下面让你的朋友给你发QQ消息、微信消息。

这是我这里测试的数据,控制打印出来:

在这里插入图片描述

QQ、微信、短信、来电都监听到了。

四、页面显示消息类型


现在只是在NotifyService中可以打印出来,那么Activity并不知道,但是实际的UI操作又是在Activity里面,因此需要将消息传递到Activity,这种方式很多,我这里使用接口回调的方式来进行。下面新建一个接口,代码如下:

public interface NotifyListener {

/**

  • 接收到通知栏消息

  • @param type

*/

void onReceiveMessage(int type);

/**

  • 移除掉通知栏消息

  • @param type

*/

void onRemovedMessage(int type);

}

然后再写一个NotifyHelper帮助类,用于实现接口的回调处理。

public class NotifyHelper {

private static NotifyHelper instance;

public static final int N_MESSAGE = 0;

public static final int N_CALL = 1;

public static final int N_QQ = 2;

public static final int N_WX = 3;

private NotifyListener notifyListener;

public static NotifyHelper getInstance() {

if (instance == null) {

instance = new NotifyHelper();

}

return instance;

}

/**

  • 收到消息

  • @param type 消息类型

*/

public void onReceive(int type) {

if (notifyListener != null) {

notifyListener.onReceiveMessage(type);

}

}

/**

  • 移除消息

  • @param type 消息类型

*/

public void onRemoved(int type) {

if (notifyListener != null) {

notifyListener.onRemovedMessage(type);

}

}

/**

  • 设置回调方法

  • @param notifyListener 通知监听

*/

public void setNotifyListener(NotifyListener notifyListener) {

this.notifyListener = notifyListener;

}

}

最后收到服务中收到通知进行调用。

在这里插入图片描述

移除通知进行调用

在这里插入图片描述

最后只要在MainActivity中实现接口。

在这里插入图片描述

这里实现接口,然后将收到的结果显示在TextView上,实现接口中的两个回调方法。

/**

  • 收到通知

  • @param type 通知类型

*/

@Override

public void onReceiveMessage(int type) {

switch (type) {

case N_MESSAGE:

textView.setText(“收到短信消息”);

break;

case N_CALL:

textView.setText(“收到来电消息”);

break;

case N_WX:

textView.setText(“收到微信消息”);

break;

case N_QQ:

textView.setText(“收到QQ消息”);

break;

default:

break;

}

}

/**

  • 移除通知

  • @param type 通知类型

*/

@Override

public void onRemovedMessage(int type) {

switch (type) {

case N_MESSAGE:

textView.setText(“移除短信消息”);

break;

case N_CALL:

textView.setText(“移除来电消息”);

break;

case N_WX:

textView.setText(“移除微信消息”);

break;

case N_QQ:

textView.setText(“移除QQ消息”);

break;

default:

break;

}

}

下面再运行一下:

在这里插入图片描述

可以看到,现在通过接口想消息类型的结果显示到页面上来了。

五、页面显示消息内容、时间


现在的很多带屏幕的手环都做到了这一点,可以显示消息内容,这个说起来很高大上,实际上很简单,还是之前的那个地方,那个位置,为了更够更好的显示内容,我还是用代码来说明一下。

首先在NotifyListener增加接口中的方法。

/**

  • 接收到通知栏消息

  • @param sbn

*/

void onReceiveMessage(StatusBarNotification sbn);

/**

  • 移除掉通知栏消息

  • @param sbn

*/

void onRemovedMessage(StatusBarNotification sbn);

与之前的方法中的参数不同,当然图方便也可以只用这个新增的,把之前的可以去掉,因为现在的这个拿到的信息要比之前多,只不过需要再对消息做进一步的处理。

接口方法写好了,在NotifyHelper中新增两个方法对刚才的接口方法进行调用。

/**

自我介绍一下,小编13年上海交大毕业,曾经在小公司待过,也去过华为、OPPO等大厂,18年进入阿里一直到现在。

深知大多数Android工程师,想要提升技能,往往是自己摸索成长或者是报班学习,但对于培训机构动则几千的学费,着实压力不小。自己不成体系的自学效果低效又漫长,而且极易碰到天花板技术停滞不前!

因此收集整理了一份《2024年Android移动开发全套学习资料》,初衷也很简单,就是希望能够帮助到想自学提升又不知道该从何学起的朋友,同时减轻大家的负担。
img
img
img
img
img
img
img

既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,基本涵盖了95%以上Android开发知识点,真正体系化!

由于文件比较大,这里只是将部分目录大纲截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频,并且后续会持续更新

如果你觉得这些内容对你有帮助,可以添加V获取:vip204888 (备注Android)
img

题外话

不管怎么样,不论是什么样的大小面试,要想不被面试官虐的不要不要的,只有刷爆面试题题做好全面的准备,当然除了这个还需要在平时把自己的基础打扎实,这样不论面试官怎么样一个知识点里往死里凿,你也能应付如流啊

这里我为大家准备了一些我工作以来以及参与过的大大小小的面试收集总结出来的一套进阶学习的视频及面试专题资料包,主要还是希望大家在如今大环境不好的情况下面试能够顺利一点,希望可以帮助到大家~

欢迎评论区讨论。

一个人可以走的很快,但一群人才能走的更远。不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎扫码加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!
img
习提升的进阶课程,基本涵盖了95%以上Android开发知识点,真正体系化!**

由于文件比较大,这里只是将部分目录大纲截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频,并且后续会持续更新

如果你觉得这些内容对你有帮助,可以添加V获取:vip204888 (备注Android)
[外链图片转存中…(img-xGAj2UE5-1712771058597)]

题外话

不管怎么样,不论是什么样的大小面试,要想不被面试官虐的不要不要的,只有刷爆面试题题做好全面的准备,当然除了这个还需要在平时把自己的基础打扎实,这样不论面试官怎么样一个知识点里往死里凿,你也能应付如流啊

这里我为大家准备了一些我工作以来以及参与过的大大小小的面试收集总结出来的一套进阶学习的视频及面试专题资料包,主要还是希望大家在如今大环境不好的情况下面试能够顺利一点,希望可以帮助到大家~

[外链图片转存中…(img-Jhwr1iaT-1712771058598)]

欢迎评论区讨论。

一个人可以走的很快,但一群人才能走的更远。不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎扫码加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!
[外链图片转存中…(img-zQ7C8Riw-1712771058598)]

  • 3
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,下面是使用BroadcastReceiver实时监听电量的Android源码: 1. 在AndroidManifest.xml文件中添加以下权限和广播接收器: ```xml <uses-permission android:name="android.permission.BATTERY_CHANGED" /> <receiver android:name=".BatteryReceiver"> <intent-filter> <action android:name="android.intent.action.BATTERY_CHANGED" /> </intent-filter> </receiver> ``` 2. 创建BatteryReceiver类实现BroadcastReceiver接口,重写onReceive()方法: ```java public class BatteryReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1); int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1); float batteryLevel = level / (float) scale; Log.d("BatteryLevel", batteryLevel * 100 + "%"); } } ``` 3. 在MainActivity中注册广播接收器: ```java public class MainActivity extends AppCompatActivity { private BatteryReceiver batteryReceiver; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // 注册广播接收器 batteryReceiver = new BatteryReceiver(); IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction(Intent.ACTION_BATTERY_CHANGED); registerReceiver(batteryReceiver, intentFilter); } @Override protected void onDestroy() { super.onDestroy(); // 取消注册广播接收器 unregisterReceiver(batteryReceiver); } } ``` 这样就可以实时监听电量了。当电量发生变化时,会在Logcat中输出当前电量百分比。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值