本篇通过BroadcastReceiver模拟手机电量查看,通过AlertDialog进行电量信息提示
同时这也是中国大学慕课移动终端应用开发的网课作业17,我会持续更新我的作业,如果有需要关注一下吧
学习建议1.Broadcast有关知识可看:Android 之 超详细 Broadcast
2.了解Intent.ACTION_BATTERY_CHANGED中携带数据可看:监听电池变化的广播中携带的数据
3.常用Intent可看:android 系统Intent合集
效果图 代码实现 MyReceiver.javapublic class MyReceiver extends BroadcastReceiver {
private int level;//保存电量的值
@Override
public void onReceive(Context context, Intent intent) {
//获取电量信息并保存
int level = intent.getIntExtra("level", 0);
this.level = level;
}
public int getLevel() {
return level;
}
public void setLevel(int level) {
this.level = level;
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
private Button mButton;
private MyReceiver mReceiver;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mButton = findViewById(R.id.send);
//设置过滤器
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
mReceiver = new MyReceiver();
//动态注册
registerReceiver(mReceiver, intentFilter);
//给按钮添加弹出对话框事件
mButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
AlertDialog.Builder d = new AlertDialog.Builder(MainActivity.this);
d.setTitle("系统提示")
.setMessage("当前剩余电量低于"+mReceiver.getLevel()+"%,请及时充电")//获取电量这个属性
.setIcon(R.mipmap.ic_launcher)
.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(MainActivity.this,"点击了确定",Toast.LENGTH_SHORT).show();
}
})
.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(MainActivity.this,"点击了取消",Toast.LENGTH_SHORT).show();
}
})
.setNeutralButton("忽略", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(MainActivity.this,"点击了忽略",Toast.LENGTH_SHORT).show();
}
});
d.create().show();
}
});
}
}
activity_main.xml
总结
如果有什么问题,请私信联系我或者在评论区留言
码字不易,若有帮助,给个关注和赞呗