[英]Detect USB STATE CHANGE android java
I want to be able to trigger an event when a user connects or disconnects a USB device. 我希望能够在用户连接或断开USB设备时触发事件。 I have the following code: 我有以下代码:
public static boolean isConnected(Context context) {
Intent intent = context.registerReceiver(null, new IntentFilter("android.hardware.usb.action.USB_STATE"));
return intent.getExtras().getBoolean("connected");
}
The above is from another StackOverflow question. 上面是来自另一个StackOverflow问题。
How can I go about the problem I'm facing? 我该如何解决所面临的问题? I don't think it would be practical to check every x second if the state has changed. 我认为如果状态发生变化,每隔x秒检查一次是不切实际的。 So, I checked online for an event listener about USB_CONNECTION, but I can't seem to find any. 因此,我在线检查了有关USB_CONNECTION的事件侦听器,但似乎找不到任何侦听器。 Actually, I did find a few but they were confusing and quite old. 实际上,我确实找到了一些,但是它们令人困惑并且相当古老。 (A year or two ago.) (一两年前。)
TRIED CODE 尝试码
while(notFinished) {
if (!isConnected(this)) {
pause();
} else if (!mediaPlayer.isPlaying() && isConnected(this)) {
play();
} else {
Log.e("[ERROR]: ", "An error has occured at startSong!");
}
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
^^^ Clearly not efficient, but it does work (somewhat). ^^^显然效率不高,但是确实可以(有些)。 So, that's why I came over here to know if there was a listener for USB_CONNECTION_STATUS. 因此,这就是为什么我来到这里了解是否存在USB_CONNECTION_STATUS的侦听器的原因。 I think this would be a lot faster. 我认为这会快很多。
You can use BroadcastReceiver for receiving connected and disconnected actions: 您可以使用BroadcastReceiver接收已连接和已断开的操作:
BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getExtras().getBoolean("connected")) {
//start doing something for state - connected
} else {
//start doing something for state - disconnected
}
}
};
IntentFilter filter = new IntentFilter();
filter.addAction("android.hardware.usb.action.USB_STATE");
registerReceiver(receiver, filter);
This BroadcastReceiver will receive actions every time wen usb connected or disconnected. 每当连接或断开USB连接时,此BroadcastReceiver都会接收操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.