问题
I have an app on the android market and users often connect their devices to their computers to add music into the apps folder. I have specifically stated in the instructions that android apps cannot communicate with the sd card while usb connected mode is enabled. Apparently this is not stupid proof enough. Is there a way to detect in java if the USB is connected? I have seen it done with broadcast receivers, but this is such a stupid way to do it. This won't work if the user starts the app after connecting to USB. There has got to be a better way.
回答1:
This is similar to this: Check USB Connection Status on Android
Although they do make use of Broadcast Receivers. You say this is a stupid way of doing things, but can you be more specific about that?
It is not the case that you can't detect it after the app has started. What you would need to do would be to put
<intent-filter>
<action android:name="android.intent.action.ACTION_UMS_CONNECTED"/>
<action android:name="android.intent.action.ACTION_UMS_DISCONNECTED"/>
in your AndroidManifest.xml underneath the <Receiver>
entry for the following class:
public class IntentReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
if(intent.getAction().equals(Intent.ACTION_UMS_CONNECTED)){
Toast.makeText(context, "mounted", Toast.LENGTH_LONG).show();
Intent myStarterIntent = new Intent(context, tst.class);
myStarterIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(myStarterIntent);
}
}
}
`
Sources Cited: http://www.anddev.org/start_activity_on_usb_connect-t8814.html
回答2:
A1: You said "users often connect their devices to their computers to add music into the apps folder", I guess you mean that the Sd card has connected to PC in MassStorage
mode, you can check this as following:
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_SHARED.equals(state)) {
// Sd card has connected to PC in MSC mode
}
A2: You said "This won't work if the user starts the app after connecting to USB", I can't agree with you, in ICS, you can register a receiver to listen android.hardware.action.USB_STATE
changes, the intent broadcasted by system is in STICKY mode, that to say even the receiver in your app is registered after usb cable connecting, you can also get this message:
Intent intent = context.registerReceiver(...);
if (intent != null) {
boolean isConnected = intent.getBooleanExtra(USB_CONNECTED, false);
boolean isMscConnection = intent.getBooleanExtra(USB_FUNCTION_MASS_STORAGE, false);
}
the intent returned in the method mentioned above the message you missed before usb cable connection to PC.
refer to the link below for details: http://www.androidadb.com/source/toolib-read-only/frameworks/base/core/java/android/hardware/usb/UsbManager.java.html
来源:https://stackoverflow.com/questions/8797792/how-to-check-if-usb-connected-mode-is-enabled-on-android