BroadcastReceiver-监听电量并将其显示在屏幕上
上个博客我展示了如何监听电量变化,但是那个过于简陋,没有将电量显示到屏幕上的功能。
这个功能看起来似乎当然没什么用,但是却是之后学习的基础。
package com.example.broadcastapplication; import androidx.appcompat.app.AppCompatActivity; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.BatteryManager; import android.os.Bundle; import android.util.Log; import android.widget.TextView; public class MainActivity extends AppCompatActivity { private static final String TAG = "MainActivity"; private TextView mBatteryLevelText; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // initView(); registerBatteryReceiver(); } private void initView() { mBatteryLevelText = (TextView) this.findViewById(R.id.battery_level); } private void registerBatteryReceiver() { //2.收听电量变化 IntentFilter intentFilter = new IntentFilter(); //3.设置频道 intentFilter.addAction(Intent.ACTION_BATTERY_CHANGED); //4. BatteryLevelReceiver batteryLevelReceiver = new BatteryLevelReceiver(); //5.注册广播 this.registerReceiver(batteryLevelReceiver,intentFilter); } //1.首先创建一个广播接收者,继承自 BroadcastReceiver private class BatteryLevelReceiver extends BroadcastReceiver{ @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); Log.d(TAG,"收到了电量变化的广播 action is =="+ action); if (mBatteryLevelText != null) { mBatteryLevelText.setText("当前电量:"+intent.getIntExtra(BatteryManager.EXTRA_LEVEL,0)); } } } }
我把电量广播注册重构成了一个方法
然后在主页面写了一个TextView
mBatteryLevelText != null 实际上非常重要,防止我们出现空指针异常
intent.getIntExtra(BatteryManager.EXTRA_LEVEL 则是获取电量数值的方式
接下来看看效果,如你所见,电量数值会随着变化
很简单,但也非常基础!
作者:冰稀饭Aurora
出处:https://www.cnblogs.com/rsy-bxf150/p/17205090.html
版权:本作品采用「署名-非商业性使用-相同方式共享 4.0 国际」许可协议进行许可。
分类:
Android学习
, 我的学习笔记-日常学习总结
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 零经验选手,Compose 一天开发一款小游戏!
· 因为Apifox不支持离线,我果断选择了Apipost!
· 通过 API 将Deepseek响应流式内容输出到前端