Here another developer tried to access the filesystem of an USB Stick within the Android SDK.
But USB Host Mode can only access USB Devices in Raw Mode. Here the Android SDK Documentation tells us that FileStream-Operations are available in USB Accessory Mode
But how to implement that? The code examples are all incomplete.
Here's the code:
private TextView textView;
private PendingIntent mPermissionIntent;
private static final String ACTION_USB_PERMISSION =
"com.android.example.USB_PERMISSION";
private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
textView = (TextView) findViewById(R.id.textView);
textView.setText("onReceive()... ");
String action = intent.getAction();
if (ACTION_USB_PERMISSION.equals(action)) {
synchronized (this) {
UsbAccessory accessory = (UsbAccessory) intent.getParcelableExtra(UsbManager.EXTRA_ACCESSORY);
if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
textView.setText("accessing... ");
if(accessory != null){
//call method to set up accessory communication
}
}
else {
Log.d("onCreate()", "permission denied for accessory " + accessory);
textView.setText("permission denied for accessory ");
}
}
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_slideshow);
UsbManager mUsbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
mPermissionIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_USB_PERMISSION), 0);
IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
registerReceiver(mUsbReceiver, filter);
}
But my app doesn't recognize any connected USB Stick. The programm doesn't even jump into the onReceive()
-Method.
Manifest file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="slideshow.xappo.de.xappo_slideshow" >
<uses-feature android:name="android.hardware.usb.accessory" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".Slideshow"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<intent-filter>
<action android:name="android.hardware.usb.action.USB_ACCESSORY_ATTACHED" />
</intent-filter>
</activity>
</application>
Does someone have example code how to create a directory on an USB stick and copy some files from the USB stick?
Best Regards