检查设备是否已插入 [英] Check if device is plugged in

查看:85
本文介绍了检查设备是否已插入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用有一个广播接收器,用于监听对 ACTION_POWER_CONNECTED ,然后依次标记屏幕以保持打开状态.

My app has a broadcast receiver to listen for changes to ACTION_POWER_CONNECTED, and in turn flag the screen to stay on.

我缺少的是该应用程序在首次运行时检查充电状态的功能.谁能帮我提供代码以手动检查充电状态吗?

What I am missing is the ability for the app to check the charging status when it first runs. Can anyone please help me with code to manually check charging status?

推荐答案

感谢CommonsWare,这是我编写的代码.

Thanks to CommonsWare here is the code I wrote.

public class Power {
    public static boolean isConnected(Context context) {
        Intent intent = context.registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
        int plugged = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
        return plugged == BatteryManager.BATTERY_PLUGGED_AC || plugged == BatteryManager.BATTERY_PLUGGED_USB || plugged == BatteryManager.BATTERY_PLUGGED_WIRELESS;
    }
}

if (Power.isConnected(context)) {
    ...
}

或Kotlin版本

object Power {
    fun isConnected(context: Context): Boolean {
        val intent = context.registerReceiver(null, IntentFilter(Intent.ACTION_BATTERY_CHANGED))
        val plugged = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1)
        return plugged == BatteryManager.BATTERY_PLUGGED_AC || plugged == BatteryManager.BATTERY_PLUGGED_USB || plugged == BatteryManager.BATTERY_PLUGGED_WIRELESS
    }
}

http://developer.android.com/training/Monitoring-device-state/battery-monitoring.html

这篇关于检查设备是否已插入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆