I am developing an Android application using Android Studio 0.5.2.
My application is operating a USB host which appears to operate correctly - unless the device is connected (and permissions have not yet been granted) when the app starts.
Generally, what happens when the USB is connected (while app is running):
"onResume" is called - this detects the device and asks for permission. An intent filter is created to catch when the USB is attached, detached or permission granted
Permission request is shown, select Ok
"onResume" is called again. The first line of this funciton is "super.onResume()"
As soon as I step over super.onResume, "Unfortunately, System UI has stopped" message is displayed and the Android UI crashes
My application continues to work correctly
If I connect the device while the application is already running there is no issue - this only occurs when the USB is connected on launch.
Any insight into what could be causing this or how to further narrow down on the problem would be greatly appreciated. I have attached the notable code below. I am not normally a Java developer, so I suspect the issue is something to do with the pause/resume behaviour, receivers, intent filters or permissions.
// *************************************************************
// ************************* USB Stuff *************************
// *************************************************************
boolean resumePermissionBlocked = false;
PendingIntent pendingIntent = null;
BroadcastReceiver receiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
// Get the information about what action caused this event
try {
String action = intent.getAction();
Log.i(TAG, "$EC: action:" + action);
if ("com.android.example.USB_PERMISSION".equals(action)) {
UsbDevice device = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
if (device != null) {
if (device.getProductId() == 0xAAAA) {
if (device.getVendorId() == 0xBBBB) {
// see if we have permission
UsbManager openManager = (UsbManager) context.getSystemService(Context.USB_SERVICE);
// send a message to the worker thread to begin opening a connection to this device
ThreadMsg msg = new ThreadMsg();
msg.request = MsgRequest.openConnection;
msg.objectA = device;
msg.objectB = openManager;
sendMessageToWorker(msg);
}
}
}
} else {
if (device != null)
Log("USB Permission denied", TextFormat.StrongWarning_withTime);
}
}
if (UsbManager.ACTION_USB_DEVICE_ATTACHED.equals(action)) {
UsbDevice device = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
if (device == null) return;
if (device.getProductId() == 0x003C) {
if (device.getVendorId() == 0x04D8) {
// see if we have permission
UsbManager openManager = (UsbManager) context.getSystemService(Context.USB_SERVICE);
if (!openManager.hasPermission(device)) {
resumePermissionBlocked = true; // block the resume function from trying to re-ask for permission
openManager.requestPermission(device, mPermissionIntent);
return;
}
ThreadMsg msg = new ThreadMsg();
msg.request = MsgRequest.openConnection;
msg.objectA = device;
msg.objectB = openManager;
sendMessageToBootloader(msg);
}
}
} else if (UsbManager.ACTION_USB_DEVICE_DETACHED.equals(action)) {
// If it was a USB device detach event, then get the USB device
// that caused the event from the intent.
UsbDevice device = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
ThreadMsg msg = new ThreadMsg();
msg.request = MsgRequest.closeConnection;
msg.objectA = device;
sendMessageToBootloader(msg);
}
} catch (Exception e) {
Log.i(TAG, "onResume catch: " + e.toString());
}
}
};
boolean receiverHasBeenRegistered = false;
PendingIntent mPermissionIntent;
#Override
public void onResume(){
try {
super.onResume();
if (resumePermissionBlocked) {
// this was resumed from a permission request - don't try to connect to the device now, leave it for the USB_PERMISSION_GRANTED intent
resumePermissionBlocked = false; // clear the flag
} else {
UsbManager manager = (UsbManager) getSystemService(Context.USB_SERVICE);
HashMap<String, UsbDevice> deviceList = manager.getDeviceList();
if (deviceList != null) {
Iterator<UsbDevice> deviceIterator = deviceList.values().iterator();
Log.i(TAG, "$EC: Begin iteration");
while (deviceIterator.hasNext()) {
// Is this the device we are after?
UsbDevice device = deviceIterator.next();
if (device == null) return;
if (device.getProductId() == 0xAAAA) {
if (device.getVendorId() == 0xBBBB) {
// see if we have permission
UsbManager openManager = (UsbManager) this.getSystemService(Context.USB_SERVICE);
if (!openManager.hasPermission(device)) {
resumePermissionBlocked = true; // block the subsequent call to this (between the application resuming and permission being granted)
openManager.requestPermission(device, mPermissionIntent);
return;
}
ThreadMsg msg = new ThreadMsg();
msg.request = MsgRequest.openConnection;
msg.objectA = device;
msg.objectB = openManager;
sendMessageToWorker(msg);
}
}
}
}
}
} catch (Exception e)
{
Log.i(TAG, "onResume catch: " + e.toString());
}
if (!receiverHasBeenRegistered) {
// this line is for permissions
mPermissionIntent = PendingIntent.getBroadcast(this, 0, new Intent("com.android.example.USB_PERMISSION"), 0);
//Create a new filter to detect USB device events
IntentFilter filter = new IntentFilter();
filter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);
filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
filter.addAction("com.android.example.USB_PERMISSION");
registerReceiver(receiver, filter);
pendingIntent = PendingIntent.getBroadcast(this, 0, new Intent(getPackageName() + ".USB_PERMISSION"), 0);
receiverHasBeenRegistered = true;
}
}
#Override
public void onPause() {
/* unregister any receivers that we have */
try {
if (receiver != null && receiverHasBeenRegistered) {
unregisterReceiver(receiver);
receiverHasBeenRegistered = false;
}
} catch (Exception e) {
// if this happens, then the receiver was probably never registered in the first place
Log.i(TAG, "onPause catch: " + e.toString());
}
super.onPause();
}
Try super.onResume at the end of onResume method
Alert user to connect the usb device on application start (main activity's
onCreate) if device is not connected, toast an alert msg and finish/close
the main activity
Add intend filter in manifest file allowing the app to start automatically on connecting the device
Try to capture exception printstacktrack when the UI stopped message is
shown and debug further from the exception.
Make sure to follow the steps from android doc
https://developer.android.com/guide/topics/connectivity/usb/host.html
Related
I'm trying to handle the event when a user presses "ok" or "cancel" on the automatic permission dialog presented when I connect a "known" USB device to the android phone.
I'm using the android.usb.host library and can send and receive between the android phone and the device. Futhermore do I handle the "USB_DEVICE_ATTACHED" and "USB_DEVICE_DETACHED" using a BroadcastReceiver without any problems.
I want to enable a sort of "autoconnect" feature and therefore I need to know when the user has pressed "ok" in the automatically displayed permission dialog, but I can't find anything online at all. All I find is "bypass dialog", but this is not what I want or need.
When I connect the usb device to the android phone, a permission dialog is automatically displayed because I use the "device_filter.xml" solution from androids documentation which can be seen here Android Usb Docs.
This is how I handle the USB_DEVICE_ATTATCHED and USB_DEVICE_DETACHED events:
public NativeUsbService(ReactApplicationContext reactContext) {
...
// register device attached/detached event listeners
IntentFilter filter = new IntentFilter();
filter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);
filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
reactContext.registerReceiver(usbReceiver, filter);
...
}
And then the Broadcast Receiver:
private final BroadcastReceiver usbReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(UsbManager.ACTION_USB_DEVICE_ATTACHED)) {
synchronized (this) {
UsbDevice device = (UsbDevice) intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
if(device != null){
usbDevice = device;
} else {
Log.d(TAG, "onReceive: DEVICE WAS ATTACHED AND WAS NULL :(");
}
}
} else if (action.equals(UsbManager.ACTION_USB_DEVICE_DETACHED)) {
Log.d(TAG, "onReceive: Device was detached!");
if(connection != null) {
connection.releaseInterface(usbDeviceInterface);
connection.close();
}
connection = null;
usbDevice = null;
endpointIn = null;
endpointOut = null;
}
}
};
I have tried multiple different approaches, but nothing has worked.
I have tried getting the user response in from the intent, like with a manual permission request like below:
private final BroadcastReceiver usbReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(UsbManager.ACTION_USB_DEVICE_ATTACHED)) {
synchronized (this) {
UsbDevice device = (UsbDevice) intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
if(device != null){
usbDevice = device;
// THIS DOES NOT WORK ↓↓↓
if(intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
// The code never gets here...
}
} else {
Log.d(TAG, "onReceive: DEVICE WAS ATTACHED AND WAS NULL :(");
sendEvent("onDeviceAttached", false);
}
}
} else if (action.equals(UsbManager.ACTION_USB_DEVICE_DETACHED)) {
if(connection != null) {
connection.releaseInterface(usbDeviceInterface);
connection.close();
}
connection = null;
usbDevice = null;
endpointIn = null;
endpointOut = null;
}
}
};
I have also tried by adding a usb permission listener to the broadcast receiver by first adding the action name to my class variables:
private static final String ACTION_USB_PERMISSION = "com.android.example.USB_PERMISSION";
Then adding the action to my intent filter like so:
public NativeUsbService(ReactApplicationContext reactContext) {
// register device attached/detached event listeners
IntentFilter filter = new IntentFilter();
filter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);
filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
filter.addAction(ACTION_USB_PERMISSION); // added action to my intent filter
reactContext.registerReceiver(usbReceiver, filter);
}
And finally reacting to the action like so:
private final BroadcastReceiver usbReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(UsbManager.ACTION_USB_DEVICE_ATTACHED)) {
synchronized (this) {
UsbDevice device = (UsbDevice) intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
if(device != null){
usbDevice = device;
}
}
} else if (action.equals(UsbManager.ACTION_USB_DEVICE_DETACHED)) {
Log.d(TAG, "onReceive: Device was detached!");
if(connection != null) {
connection.releaseInterface(usbDeviceInterface);
connection.close();
}
connection = null;
usbDevice = null;
endpointIn = null;
endpointOut = null;
sendEvent("onDeviceDetached", true);
}
else if (action.equals(ACTION_USB_PERMISSION)) {
Log.d(TAG, "onReceive: ACTION_USB_PERMISSION");
if(intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
Log.d(TAG, "onReceive: EXTRA_PERMISSION_GRANTED = true");
} else Log.d(TAG, "onReceive: EXTRA_PERMISSION_GRANTED = false");
}
}
};
Please make me aware of any missing information.
Any help is greatly appreciated.
Answering my own question in case someone else is facing the same issue.
I though about manually requesting the permission again, after permission was granted, since it is possible to handle this manual permission request when user presses an option in the dialog. I discarded this idea, not because it wouldn't work, but because I saw it as unecessary for the user to also have to press another dialog after the initial (automatic dialog).
I must add that I have not implemented this solution, so I do not know with certainty that it would prompt the user again, but I have had trouble with the manual permission request previously. If you want to try this approach the method belongs to the UsbManager class and is invoke like so usbManger.requestPermission(usbDevice).
I ended up with a solution where I start a thread which runs a loop calling usbManager.hasPermission(usbDevice) until it has permission and then emits an event (emitting this event is my use case, implement it how you like).
The solution can be seen here:
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbDeviceConnection;
import android.hardware.usb.UsbManager;
import com.facebook.react.bridge.ReactApplicationContext;
...
private static volatile boolean permissionThreadShouldStop = false;
private static Thread activePermissionThread = null;
...
public static void usbPermissionEventEmitter(ReactApplicationContext reactContext, UsbManager usbManager, UsbDevice usbDevice) {
if((activePermissionThread != null && activePermissionThread.isAlive())) {
activePermissionThread.interrupt();
}
permissionThreadShouldStop = false;
activePermissionThread = new Thread(new Runnable() {
#Override
public void run() {
while (!usbManager.hasPermission(usbDevice) && !permissionThreadShouldStop) {
try {
Thread.sleep(30);
} catch (InterruptedException e) {
e.printStackTrace();
break;
}
}
if(usbManager.hasPermission(usbDevice)) {
sendEvent(reactContext, "onUsbPermissionGranted", true);
}
}
});
activePermissionThread.start();
}
The ReactApplicationContext can be swapped with the normal android context. But this is for a react native module, so I use the reactContext.
I hope this will be helpful for someone, because i'm honestly really surpriced how scarse the android documentation is in regards to implementing Usb functionality using the android.hardware.usb library.
Also in general when searching for information online, I have often found myself lost since there is very little information on this subject.
It's my first time working with Bluetooth module in Android, I'm trying to scan devices not paired yet and show them in a message but it doesn't work. I have tried a lot of things but nothing. I have all the permissions needed. This is part of my code
mScanBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
//registerReceiver(mBroadcastReceiver, filter);
if(mBlueAdapter!=null && mBlueAdapter.isEnabled()) {
listAdapter.clear();
mBlueAdapter.startDiscovery();
showToast("Discovery");
IntentFilter filtera = new IntentFilter();
filter.addAction(BluetoothDevice.ACTION_FOUND);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
registerReceiver(mBroadcastReceiver, filter);
}
And this is my BroadcastReceiver
private final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
#Override public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
listAdapter.add(device.getName() + device.getAddress());
listAdapter.notifyDataSetChanged();
showToast("Action Scan Mode " );
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)){
mpossibleBtn.setText("Scanning Bluetooth Devices");
showToast("Scannning Bluetooth Devices... " );
} else if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)){
mpossibleBtn.setText("Scanning in progress...");
showToast("Scanning in progress... " );
}
if (action.equals(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED)) {
showToast("Action Scan Mode " );
int modeValue=intent.getIntExtra(BluetoothAdapter.EXTRA_SCAN_MODE, BluetoothAdapter.ERROR);
if(modeValue==BluetoothAdapter.SCAN_MODE_CONNECTABLE){
mPairedTv.setText("The device is not in discoverable mode but still can receive connections");
} else if(modeValue==BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE){
mPairedTv.setText("The device is in discoverable mode");
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
String deviceName = device.getName();
String deviceHardwareAddress = device.getAddress(); // MAC address
showToast("onReceive: " + device.getName() + ": " + device.getAddress());
} else if (modeValue==BluetoothAdapter.SCAN_MODE_NONE){
mPairedTv.setText("The device is not in discoverable mode and can't receive connection");
} else{
mPairedTv.setText("Error");
}
}
}
};
I'm testing the app on my Xiaomi cellphone.
you need to ADD after registering receiver
mBtAdapter.startDiscovery();
Start discovery after registering your receiver.
IntentFilter intent = new IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
registerReceiver(mBroadcastReceiver, intent);
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mBroadcastReceiver, filter);
filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
registerReceiver(mBroadcastReceiver, filter);
mBtAdapter.startDiscovery();
Or in your case
IntentFilter filtera = new IntentFilter();
filter.addAction(BluetoothDevice.ACTION_FOUND);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
registerReceiver(mBroadcastReceiver, filter);
mBtAdapter.startDiscovery();
Also ensure you have bt permissions on your manifest
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.BLUETOOTH" />
On some phones you will need to restart the adapter first.
mBluetoothAdapter.disable();
mBluetoothAdapter.enable();
for some time on the broadcast receiver if you don't receive BluetoothAdapter.ACTION_DISCOVERY_STARTED after starting discovery, you have to prompt device restart as the bt may not be working properly.you can use a timer to check this.
Ok so I just found my error. In this case BLUETOOTH and BLUETOOTH_ADMIN permissions have a protection Level of normal, and so all you need to do is request them in the manifest. The location permissions are dangerous, though, and so on Android 6.0+ devices, with a targetSdkVersion of 23 or higher, you need to request those at runtime.
I alredy have the permissions however, we do need to request ACCESS_COARSE_LOCATION at runtime.
This time the code works
mScanBtn.setOnClickListener(new View.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
public void onClick(View v) {
if(mBlueAdapter!=null && mBlueAdapter.isEnabled()) {
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
filter.addAction(BluetoothDevice.ACTION_FOUND);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
registerReceiver(mBroadcastReceiver, filter);
if (context.checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
if (mMap != null) {
mMap.setMyLocationEnabled(true);
mBlueAdapter.startDiscovery();
}
}
else {
// Permission to access the location is missing. Show rationale and request permission
PermissionUtils.requestPermission(MainActivity.this, MY_PERMISSIONS_REQUEST_LOCATION,
Manifest.permission.ACCESS_FINE_LOCATION, true);
mBlueAdapter.startDiscovery();
}
}
});
I am trying to discover all available bluetooth devices and pass to another activity.
However even when looking at the Android Docs, I am unable to figure out why I cannot discover any devices and my ArrayList remains empty.
OnClick execute this:
mBluetoothAdapter.startDiscovery();
My broadcast listener also works but nothing is every returned and ArrayList remains empty.
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
mDeviceList.add(device);
showToast("Found device " + device.getName());
}
if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)) {
final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR);
if (state == BluetoothAdapter.STATE_ON) {
showToast("Enabled");
showEnabled();
}
}
if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) {
mDeviceList = new ArrayList<>();
mProgressDlg.show();
}
if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
mProgressDlg.dismiss();
Intent newIntent = new Intent(MainScreen.this, DeviceListActivity.class);
if (mDeviceList.isEmpty()){
Log.d("onReceive: ", "EMPTY");
}
newIntent.putParcelableArrayListExtra("device.list", mDeviceList);
startActivity(newIntent);
}
}
};
GIST
Answered my own question.
The fix was to turn location on with app permissions.
Apparently this is required for Android Marshmallow
I'm currently making an app that adapt the volume depending on the bluetooth device you are connected to.
I am having issue when I want to change the volume of the music
My app detect when a bluetooth device is connected and it can change the volume but it is like it goes too quickly
Here is some of the code:
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
BluetoothDevice d = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)) {
deviceConnected(d);
}
else if (BluetoothDevice.ACTION_ACL_DISCONNECTED.equals(action)) {
deviceDisconnected(d);
}
}
};
private void deviceConnected(BluetoothDevice bluetoothDevice) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
boolean showToasts = prefs.getBoolean("show_toasts", false);
if (showToasts) { Toast.makeText(this, getResources().getString(R.string.connected_to) + " " + bluetoothDevice.getName(), Toast.LENGTH_SHORT).show(); }
mDeviceDAO = new DeviceDAO(this);
mDeviceDAO.open();
DeviceOptions device = mDeviceDAO.select(bluetoothDevice.getAddress());
if (device == null) { return; }
if(device.getActivated() == 0) {
return;
}
int v = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
saveLastVolume(v);
int volume = device.getVolume();
int flag = 0;
if(prefs.getBoolean("show_am_ui", false)) {
flag = AudioManager.FLAG_SHOW_UI;
}
mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC,
volume,
flag);
}
If add a delay of around 3000ms when I change the volume, it will work properly but it's not a clean solution. In fact the toast for the connection will be displayed before the bluetooth device is "completely" connected
I also found an app that do the same thing but it seems that I'm doing the same thing.
Here is its githublink
What's your capture is the ACL connected or ACL disconnected, yes you are right once your toast appears i.e. the ACL connected does not mean the Bluetooth profile connected(exactly what you said "completely" connected), it only means the physical connection established between two device, you might as well to receive other event, e.g. HFP/A2dp connected, that's the real profile connected.
However the ACL disconnected is the milestone that the Bluetooth connection is really disconnected.
I have a mUsbReceiver (BroadcastReceiver) and CameraActivity. The receiver setContentView(R.layout.main) from CameraActivity via an Intent. Then CamearActivity updates its View with this value. Notice that the setContentView is in the Broadcast receiver class and not in the CameraActivity Class.
public class CameraActivity extends Activity {
private static final String TAG = "openXC::Activity";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
usbConnection();
}
public void usbConnection() {
UsbManager mUsbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
PendingIntent mPermissionIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_USB_PERMISSION), PendingIntent.FLAG_CANCEL_CURRENT);
IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
registerReceiver(mUsbReceiver, filter);
String txt = "default";
HashMap<String, UsbDevice> deviceList = mUsbManager.getDeviceList();
Log.i(TAG, "Device List: " + deviceList);
Iterator<UsbDevice> deviceIterator = deviceList.values().iterator();
UsbDevice device = deviceIterator.next();
Log.i(TAG, "Device List: " + deviceList);
mUsbManager.requestPermission(device, mPermissionIntent);
}
private static final String ACTION_USB_PERMISSION ="com.ford.openxc.webcam.USB_PERMISSION";
private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (ACTION_USB_PERMISSION.equals(action)) {
synchronized (this) {
UsbDevice device = (UsbDevice)intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
if(device != null){
Log.d(TAG, "Displayed Comten View " + device);
setContentView(R.layout.main);
}
}
else {
Log.d(TAG, "permission denied for device " + device);
}
}
}
}
};
}
This works fine sometimes but sometimes throws the following error
I/openXC::Activity( 5609): Device List: {/dev/bus/usb/001/002=UsbDevice[mName=/dev/bus/usb/001/002,mVendorId=1133,mProductId=2085,mClass=239,mSubclass=2,mProtocol=1,mInterfaces=[Landroid.os.Parcelable;#421a1f50]}
I/openXC::Activity( 5609): Device List: {/dev/bus/usb/001/002=UsbDevice[mName=/dev/bus/usb/001/002,mVendorId=1133,mProductId=2085,mClass=239,mSubclass=2,mProtocol=1,mInterfaces=[Landroid.os.Parcelable;#421a1f50]}
I/Adreno200-EGLSUB( 5609): <ConfigWindowMatch:2087>: Format RGBA_8888.
E/ ( 5609): <s3dReadConfigFile:75>: Can't open file for reading
E/ ( 5609): <s3dReadConfigFile:75>: Can't open file for reading
D/openXC::Activity( 5609): Displayed Comten View UsbDevice[mName=/dev/bus/usb/001/002,mVendorId=1133,mProductId=2085,mClass=239,mSubclass=2,mProtocol=1,mInterfaces=[Landroid.os.Parcelable;#421d3ed0]
D/WebcamPreview( 5609): WebcamPreview constructed
Technically, you can call setContentView any time you are executing on the event thread.
Otherwise you need to use a Handler to call it.
Also, here are some usefull links that might help you:
link1
link 2
link 3
I dont have much exp on USB sort of thing but since u said its saying cannot readfile.. i believe dat the error may be in the usb so for the debugging purpose i would suggest to move the setContentView(int) from if conditions to the onRecieve directly so dat whenever the onReceive is called ur contenview will change , this will help to ensure that the error is not with setcontentview... After dat u can see without setcontentview in the usb and now if the error is coming then surely the error is in the usb and not in the setContentView ....
Hope it works :)