2023年1月11日

Android系統USB偵測

 



import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.usb.UsbManager;

public class USB_Detect {

public interface USB_detect_action{

public void usb_attached();


public void usb_detached();

}
public USB_detect_action usb_action=null;
private USBStatus status = new USBStatus();
private final String USB_PERMISSION = "USB";
private Activity p_activity;
public void register_detect(Activity activity){

p_activity=activity;
IntentFilter filter = new IntentFilter();
filter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);
filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
filter.addAction(USB_PERMISSION);
activity.registerReceiver(status, filter);
}

public void unregister_detect(){
p_activity.unregisterReceiver(status);
}

private class USBStatus extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action == null) return;
switch (action) {

/**偵測USB插入*/
case UsbManager.ACTION_USB_DEVICE_ATTACHED:
if(usb_action!=null){
usb_action.usb_attached();
}
break;
/**偵測USB拔除*/
case UsbManager.ACTION_USB_DEVICE_DETACHED:
if(usb_action!=null){
usb_action.usb_detached();
}
break;
}
}
}

}

沒有留言:

張貼留言