【发布时间】:2010-07-16 16:50:46
【问题描述】:
当 USB 或 AC 电源连接到 Android 手机时,是否有一种简单的方法可以收到通知?
【问题讨论】:
标签: android
当 USB 或 AC 电源连接到 Android 手机时,是否有一种简单的方法可以收到通知?
【问题讨论】:
标签: android
在 AndroidManifest.xml 中
<application android:icon="@drawable/icon" android:label="@string/app_name">
<receiver android:name=".receiver.PlugInControlReceiver">
<intent-filter>
<action android:name="android.intent.action.ACTION_POWER_CONNECTED" />
<action android:name="android.intent.action.ACTION_POWER_DISCONNECTED" />
</intent-filter>
</receiver>
</application>
在代码中
public class PlugInControlReceiver extends BroadcastReceiver {
public void onReceive(Context context , Intent intent) {
String action = intent.getAction();
if(action.equals(Intent.ACTION_POWER_CONNECTED)) {
// Do something when power connected
}
else if(action.equals(Intent.ACTION_POWER_DISCONNECTED)) {
// Do something when power disconnected
}
}
}
【讨论】:
为ACTION_BATTERY_CHANGED 设置BroadcastReceiver。额外的Intent 会告诉您充电状态是什么——详情请参阅BatteryManager。
【讨论】:
另一种方法是使用电池管理器。这我可用于 api>=21
public class PowerUtil {
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;
}
}
【讨论】:
这是另一种轮询信息的方法:
在此处读取值:例如。
通过安卓外壳:
cat /sys/class/power_supply/usb/online
1=已连接,0=未连接。反映 USB 连接状态。
cat /sys/class/power_supply/ac/online
1=已连接,0=未连接。反映交流电连接状态。
结合使用这两者,我想可以判断设备是否正在通电。不确定所有设备的位置是否相同。在 android 7+ 和 5+、三星平板电脑和 RockChip 设备上找到相同的位置。
对于我提到的测试设备,它有效。文件是 RO,只读,你只会阅读它们来轮询信息。 android API 没有提供我需要使用的版本(5.1.1)所需的详细程度,但确实如此。我使用提供的 android API 来创建一个运行这些命令的进程。它不需要根。这是为信息亭应用程序完成的。您也可以仅使用 android API(文件、FileReader 等)运行相同的进程。
这是一个 Android API 示例:
File aFile = new File("/sys/class/power_supply/ac/online");
try {
BufferedReader br = new BufferedReader(new FileReader(aFile));
char aBuff[] = new char[1];
int aCount = br.read(aBuff,0, 1);
Log.d(TAG, "run: Res:"+new String(aBuff));
}catch(Exception e){
Log.d(TAG, "Exception:Error:run: "+e.toString());
}
【讨论】:
还有一件事你必须检查Manifest --->应用程序中是否有错误。 如果然后单击显示错误的字段,然后单击链接“名称” 然后出现添加类的对话框。添加类并在类中复制接收代码。也就是说,上面的代码应该复制到类文件而不是主要活动中。 谢谢 Pzycoderz
【讨论】: