检测设备被插入

编程入门 行业动态 更新时间:2024-10-25 16:29:05
本文介绍了检测设备被插入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想能够检测设备是否插好。我希望能够只查询,同样的方式,我们可以为连接状态做。这是可能的还是我需要创建一个广播接收器监听电池事件?

I would like to be able to detect whether or not the device is plugged in. I would like to be able to just query that the same way we can do for the connectivity state. Is that possible or do I need to create a broadcast receiver that listens for the battery events?

推荐答案

显然,ACTION_BATTERY_CHANGED是一种持久广播,这意味着你可以注册并接受它已经播出后的任何时间。为了让你可以做这样的事情堵塞状态:

Apparently the ACTION_BATTERY_CHANGED is a "sticky broadcast" which means you can register for it and receive it any time after it has been broadcast. To get the plugged state you can do something like:

public void onCreate() { BroadcastReceiver receiver = new BroadcastReceiver() { public void onReceive(Context context, Intent intent) { int plugged = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1); if (plugged == BatteryManager.BATTERY_PLUGGED_AC) { // on AC power } else if (plugged == BatteryManager.BATTERY_PLUGGED_USB) { // on USB power } else if (plugged == 0) { // on battery power } else { // intent didnt include extra info } } }; IntentFilter filter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED); registerReceiver(receiver, filter); }

更多推荐

检测设备被插入

本文发布于:2023-11-05 04:11:10,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1559864.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:检测设备   被插

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!