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 :)
Related
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
Currently I developed a new method to discover bluetooh ready connections. Here is my code:
private void DiscoverOBDConnection() {
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
mBluetoothAdapter.startDiscovery();
BroadcastReceiver mReceiver;
// Create a BroadcastReceiver for ACTION_FOUND
final List<String> discoverableDevicesList = new ArrayList<String>();
mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
// When discovery finds a device
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// Get the BluetoothDevice object from the Intent
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
short rssi = intent.getShortExtra(BluetoothDevice.EXTRA_RSSI, Short.MIN_VALUE);
discoverableDevicesList.add(device.getName() + "\n" + device.getAddress() + "\n" + rssi);
String discoveredDeviceName = device.getName();
discoverableDevicesList.add(discoveredDeviceName);
}
}
};
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
context.registerReceiver(mReceiver,filter); // Don't forget to unregister during onDestroy
}
I just do not know how to call the onreceive method from another method. Could you help me to learn how to implement and discover the ready to connect bluetooth devices?
You can just send broadcast
Intent i = new Intent(BluetoothDevice.ACTION_FOUND);
sendBroadcast(i);
Or call it directly
mReceiver.onReceive(this, new Intent(BluetoothDevice.ACTION_FOUND));
i'm trying to use in my project a broadcast receiver which listens to battery status of charging/not charging and throw a toast in each of the options .
every time i change the charger status in the app ,the app crash.
(if i start the app with the charger connected it's show me the right toast
but when i uncharge the phone the app crashes)
here is the code
thanks in advance
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
Intent batteryStatus = this.registerReceiver(null, ifilter);
int status = batteryStatus.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING ||
status == BatteryManager.BATTERY_STATUS_FULL;
if(isCharging==true){
Toast.makeText(this, "Charging", Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(this, "Charger not connected", Toast.LENGTH_SHORT).show();
UPDATE
i'm having an hard time to understand what i suppose to do.
i'm pretty new so be patient with me :)
here is the code i made
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
checkBatteryState(null);
public void checkBatteryState(View sender) {
IntentFilter filter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
Intent batteryStatus = registerReceiver(null, filter);
int chargeState = batteryStatus.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
String strState;
switch (chargeState) {
case BatteryManager.BATTERY_STATUS_CHARGING:
case BatteryManager.BATTERY_STATUS_FULL:
strState = "charging";
Toast.makeText(this, strState, Toast.LENGTH_LONG).show();
break;
default:
strState = "not charging";
Toast.makeText(this, strState, Toast.LENGTH_LONG).show();
}
}
}
http://www.vogella.com/tutorials/AndroidBroadcastReceiver/article.html
is this what you're using?
Maybe you haven't ensured your Intent is sticky.
My advice would be not to use a registerreceiver with a null argument.
Try this method for creating a broadcastreceiver:
How to send data to another app which is not started
put your Toasts in the onReceive() function.
The code is not actually registering a receiver, just getting a sticky broadcast. If the broadcast has never been sent the this will return null which will cause a NPE in the remaining code.
I have a broadcastreceiver created in my Service class.
It is set to react to this action: WifiManager.SCAN_RESULTS_AVAILABLE_ACTION
So basically everytime I do a method call of wifi.startScan(); , and the results become available, the broadcastreceiver's onReceive method does its thing.
My issue is that I need to process those scan results and its likely not good practice to do so much in the broadcastreceiver. I want to do all the calculations back in my service class but I need to somehow access the ScanResults.
Any sort of help with this? As it is much needed.
Here is a simplified version of my code conveying the purpose of my broadcastreceiver:
Snippet from my Service class:
IntentFilter i = new IntentFilter();
i.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION); //reacts to the scan results being available
registerReceiver(mybroadcast,i);
wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
if(!wifi.isWifiEnabled()){ // if wifi is not enabled
toast = Toast.makeText(getApplicationContext(), "Wifi is off. Please turn it on.", Toast.LENGTH_LONG);
toast.show();
//wifi.setWifiEnabled(true);
//startActivity(backIntent);
}
else
{
wifi.startScan(); //what the receiver is going to react to
}
Code for my receiver:
private final BroadcastReceiver mybroadcast = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
//gets the scan results
wifi = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE);
List<ScanResult> scans = wifi.getScanResults();
// do some work here...
}
}
You can try adding an handler to service for ex:
private final Handler handler = new Handler() {
public void handleMessage(Message msg) {
String aResponse = msg.getData().getString("message");
if ((null != aResponse)) {
// ALERT MESSAGE
Toast.makeText(getBaseContext(),
"Server Response: " + aResponse, Toast.LENGTH_SHORT)
.show();
} else {
// ALERT MESSAGE
Toast.makeText(getBaseContext(),
"Not Got Response From Server.", Toast.LENGTH_SHORT)
.show();
}
}
};
And send a message to it in OnReceive of your BroadcastReceiver:
Message msgObj = handler.obtainMessage();
Bundle b = new Bundle();
b.putString("message", msg);
msgObj.setData(b);
handler.sendMessage(msgObj);
how is it possible to get the Bluetooth information (name, Mac address,...) of the peer device that the android device is connected to that via Bluetooth ?
You can use the following code to get all remote devices :)
private void discoveryDevice(){
// Register the BroadcastReceiver
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mReceiver, filter); // Don't forget to unregister during onDestroy
mBluetoothAdapter.startDiscovery();
}
// Create a BroadcastReceiver for ACTION_FOUND
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
// When discovery finds a device
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// Get the BluetoothDevice object from the Intent
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
Log.d(TAG, "device " + device.getName() + "\n" + device.getAddress());
}
}
};
It's really good for you to get the name of remote device throught the code:
Log.d(TAG, "device " + device.getName() + "\n" + device.getAddress());
I can't test this code at this moment but maybe can give an idea to how you can get the name and others parameters of bluetooth.
static BluetoothSocket socket ;
public static boolean btCon(Context ctx){
Method m;
try {
BluetoothDevice devc = BluetoothAdapter.getDefaultAdapter().getRemoteDevice(MAC_ADRS);
m = devc.getClass().getMethod("createRfcommSocket", new Class[]{int.class});
socket = (BluetoothSocket)m.invoke(devc, Integer.valueOf(1));
socket.connect();
String name = devc.getName();/* or */ String name2 = devc.getName().toString();
Log.i("Test","Name: "+name);
Log.i("Test","Name 2: "+name2);
return true;
}catch(Exception e)
{
return false;
}
}