检测USB连接,并检查它是否是一台PC [英] Detect USB Connection and check if it is a PC

查看:166
本文介绍了检测USB连接,并检查它是否是一台PC的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想检测wheather我的Andr​​oid手机通过USB连接或不...使用该code此i'm:

I want to detect wheather my android phone is connected via USB or not...for this i´m using this code:

public static boolean isConnected(Context context) {
    intent = context.registerReceiver(null, new IntentFilter("android.hardware.usb.action.USB_STATE"));
    return intent.getExtras().getBoolean("connected");
}

但有一种可能性,明确的知道我是否连接到PC上?由于该解决方案,我有火灾事件,即使我我的手机连接到打印机或其他事物具有USB端口...

But is there a possibility to explicit know if i am connected to a PC?! Because the Solution i have fires the Event even i connect my phone to a printer or sth else with an USB Port...

我已经尝试过刚刚发布的解决方案@nios,但如果isCharging和usbCharge布尔值设置为true,it's不guaranted您连接到PC。即使您已连接到打印机两个布尔值会赌注设置为true ...那是我的问题。

I already tried the Solution @nios just posted, but if isCharging and usbCharge booleans are set to true, it´s not guaranted that your are connected to a PC...Even if you are connected to a Printer both booleans will bet set to true...Thats my Problem

推荐答案

您可以使用此IntentFilter的:

You can use this IntentFilter :

IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
Intent batteryStatus = context.registerReceiver(null, ifilter);

// Are we charging / charged?
int status = batteryStatus.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING ||
                 status == BatteryManager.BATTERY_STATUS_FULL;

// How are we charging?
int chargePlug = batteryStatus.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
boolean usbCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_USB;
boolean acCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_AC;

如果 isCharging usbCharge 布尔值设置为true,则连接通过USB的PC。

If isCharging and usbCharge booleans are set to true, you are connected to a PC via USB.

希望这有助于。

上找到<一href="http://developer.android.com/training/monitoring-device-state/battery-monitoring.html">http://developer.android.com/training/monitoring-device-state/battery-monitoring.html

这篇关于检测USB连接,并检查它是否是一台PC的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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