我需要知道我的Android设备是否正在充电以及是否已连接到usb,因此我使用以下代码:
IntentFilter intentFilter;
Intent intent;
intentFilter= new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
intent= mContext.registerReceiver(null, intentFilter);
int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING || status == BatteryManager.BATTERY_STATUS_FULL;
int chargePlug = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
boolean usbCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_USB;
boolean acCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_AC;
我的问题是:有时候,根据测试的设备,当设备显然连接到USB(我可以通过访问所有数据文件夹告诉),它仍然返回usbCharge = false。 任何人都可以想到一个原因吗?我应该提到我总是使用相同的设备类型,只是不同的设备...
提前致谢...
答案 0 :(得分:0)
@Override
public void onReceive(Context context, Intent intent) {
Log.e("test","reciver");
final Intent mIntent = context.getApplicationContext().registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
int status = mIntent.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
//
// boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING ||
// status == BatteryManager.BATTERY_STATUS_FULL;
int chargePlug = mIntent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
boolean usbCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_USB;
boolean acCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_AC;
Log.e("test",usbCharge+"");
Toast.makeText(context,usbCharge+"",Toast.LENGTH_SHORT).show();
// Toast.makeText(context,acCharge+"",Toast.LENGTH_SHORT).show();
}