can we receive notification if user connected there phone through USB cable.
Actually there is one broadcast event; if you turned on Debug in your application settings, your will see a bug on your notification bar when you plugged usb. Following is the sample how it works;
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
// UsbManager.ACTION_USB_STATE -> "android.hardware.usb.action.USB_STATE" actually
if (action.equals(UsbManager.ACTION_USB_STATE)) {
Bundle extras = intent.getExtras();
// UsbManager.USB_CONNECTED -> "connected" actually
usbConnected = extras.getBoolean(UsbManager.USB_CONNECTED);
...
You can find this at framework/base/service/java/com/android/server/NotificationManagerService.java.
Hope this helps.
Ajay,
I wasn't able to find anything specific to just "USB Connected," but there are a few Broadcast Actions that may be of interest in this case depending on what you are trying to accomplish:
ACTION_MEDIA_SHARED: External media is unmounted because it is being shared via USB mass storage.
ACTION_UMS_CONNECTED: The device has entered USB Mass Storage mode. This is used mainly for the USB Settings panel.
ACTION_UMS_DISCONNECTED: The device has exited USB Mass Storage mode. This is used mainly for the USB Settings panel.
There doesn't seem to be a Broadcast Action specific to USB simply being plugged in, you could also try doing something with:
ACTION_POWER_CONNECTED: External power has been connected to the device.
But this would go off for both USB connected to a computer and USB connect ONLY to a power source...
Interestingly, I also found this LINK simply stating that there was no Broadcast Action for "USB Connected".
You may be out of luck in this case :-\
Since: API Level 5
An activity to run when device is inserted into a car dock. Used with ACTION_MAIN to launch an activity. For more information, see UiModeManager.
Constant Value: "android.intent.category.CAR_DOCK"
public static final String CATEGORY_CAR_MODE
Since: API Level 8
Used to indicate that the activity can be used in a car environment.
Constant Value: "android.intent.category.CAR_MODE"
A number of years later... this might help someone that came looking like I did. Since Honeycomb, there are two actions one can listen for USB_DEVICE_ATTACHED and USB_DEVICE_DETACHED.
Related
I am new to Android Things, and I'm trying to power off the usb device that connected to the i.MX7 Dual.
After I read https://developer.android.com/guide/topics/connectivity/usb/host.html#api , I find that there is no result of the VID and PID of it.
My question is that I just want to control my device via power on and power off it, how can I do it? Thanks in advance.
You can try "software" solution like this or that, but seems, better way is to use MOSFET power switch, like in this answer of yo':
which connected to GPIO pin of Android Things board. In that case you can control your device via that GPIO pin:
...
gpio.setDirection(Gpio.DIRECTION_OUT_INITIALLY_LOW);
gpio.setActiveType(Gpio.ACTIVE_HIGH);
// set your USB device ON
gpio.setValue(true);
...
I'm designing an android app, however the charging port on my phone was damaged and when I connect the computer to my phone, it says USB device not recognised. I have looked up debugging through bluetooth and wifi, however they either require a root, which needs me to connect my phone to the PC or they need that connection to set up the bluetooth/wifi debugging at first. I've been trying alternatively to use the emulator, however after fixing errors with the intel hardware acceleration, I now get a black screen whenever I launch the emulator. I would like to be able to debug on my phone, is there any workaround you can suggest that would work in this situation?
This may not be the best solution but it will let you grab logs from the device.
1. Enable the developer option on your phone if you have not done it already.
2. Enable "Bug report shortcut" or "Include bug reports in power menu" under developer options in settings. This will let you send an email with device logs attached to it.
3. Add whatever logs to your application and install it on the phone.
4. Run the app.
5. Send the logs in email using the option in power button menu.
6. Go through the logs. Go to step 3 until you fix the problem.
The .apk file may be easily transfered using Dropbox or any other filesharing service. Pick it up in the build outputs folder.
However this is not the best way to debug your app, one way of doing this would be to implement your own Log wrapper and to write your output to the file on an external storage.
A quick example would be:
public class Log {
public static int v(String tag, String msg) {
writeToLogFile(msg);
return android.util.Log.v(tag, msg);
}
public static int d(String tag, String msg) {
writeToLogFile(msg);
return android.util.Log.d(tag, msg);
}
private static void writeToLogFile(String msg){
// write to log file
}
// TODO: implement I / W / E levels logging
}
Also, how about using Fabric kit for troubleshooting.
I have an issue with getting an USBInterface from an USBDevice when the device is plugged in in an USB hub with more than one device.
When I connect the USB device directly via OTG or via a hub which is connected via OTG everything works fine but as soon as I plug in an extra device in the hub I'm not able to open a connection.
I retrieve all usb device drivers and iterate trough them until i find the device i want to communicate with.
The following code Snippet contains my method for retrieving the usb devices:
String manufacturer = "MY_MANUFACTURER" // Dummy text for this snippet
int interfaceCount; // Number of USB interfaces
UsbManager manager = (UsbManager) getSystemService(Context.USB_SERVICE);
List<UsbSerialDriver> drivers UsbSerialProber.getDefaultProber().findAllDriver(manager);
for (UsbSerialDriver serialDriver : drivers) {
// Check for my specific USB device
if (serialDriver.getDevice().getManufacturerName().equals(manufacturer)) {
interfaceCount = driver.getInterfaceCount();
}
}
When my device is the only device in the hub the number of interfaces is 2, but as soon as i add an other device the count is 0 and the system throws an ArrayIndexOutOfBoundException on getInterfaceCount as soon as i try to open a connection.
Additional Info: I use the usb-serial-for-android library as a wrapper for communicating with the device. It's either an arduino (for testing) or an FTDI chip.
We are struggeling with the same problem. It seems to be a bug in Android 5 (at least for us, you did not mention your android version). You can find the bug at
https://code.google.com/p/android/issues/detail?id=159529
or
https://www.reddit.com/r/androiddev/comments/37v2c0/usbdevice_getinterface_seems_to_be_broken_in_5x/
or
https://code.google.com/p/android/issues/detail?id=159897
Be aware that it works with Android Versions < 5 and also with Android 6.0 again. So up or downgrading Android might be a solution.
regards,
Daniel
I have achieved this problem without compiling kernel. As you know when application first created works fine but when attached new devices after application starts gets only last one and disable others. So I have created new activity that returns to mainactivity, but before app goes second activity I had killed all progress at mainactivity then goes to second activity which returns immediately to mainactivity and every thing works like firstly created.
Main Activiy Codes:
int pid = android.os.Process.myPid();
android.os.Process.killProcess(pid);
Bundle temp_bundle = new Bundle();
onSaveInstanceState(temp_bundle);
Intent intentRecreate = new Intent(MainActivity.this,SecondActivity.class);
intent.putExtra("bundle", temp_bundle);
tartActivity(intentRecreate);
finish();
Second Activity Codes:
Intent start;
start = new Intent(FreshStartActivity.this,MainActivity.class);
startActivity(start);
finish();
Thanks to: How to kill a process?
Everywhere I look I find this method "getBondedDevices()" for my bluetooth adapter. However, I have my tablet and another bluetooth device sitting next to me, and I can't figure out how to actually get the device to show up on the list of bonded devices.
In Bluetooth terms, "bonded" and "paired" are basically synonyms (officially, the process of pairing leads to a bond, but most people use them interchangeable). In order for your device to be added to that list, you must go through the process of Discovery, which is how one device searches and finds another, and then Pair the two together.
You can actually do this from the device settings as a user, but if you are looking to so so within the context of an app, your process will likely look something like this:
Register a BroadcastReceiver for BluetoothDevice.ACTION_FOUND and BluetoothAdapter. ACTION_DISCOVERY_FINISHED
Start discovery by calling BluetoothAdapter.startDiscovery()
Your receiver will get called with the first action every time a new device is found in range, and you can inspect it to see if it's the one you want to connect with. You can call BluetoothAdapter.cancelDiscovery() once you've found it to not waste the battery any more than necessary.
When discovery is complete, if you haven't canceled it, your receiver will get called with the second action; so you know not to expect any more devices.
With a device instance in hand, open a BluetoothSocket and connect(). If the devices are not already bonded, this will initiate pairing and may show some system UI for a PIN code.
Once paired, your device will show up in the bonded devices list until the user goes into settings and removes it.
The connect() method also actually opens the socket link, and when it returns without throwing an exception the two devices are connected.
Now connected, you can call getInputStream() and getOutputStream() from the socket to read and write data.
Basically, you can inspect the list of bonded devices to quickly get access to an external device, but in most applications you will be doing a combination of this and true discovery to make sure you can always connect to the remote device regardless of what the user does. If a device is already bonded, you'd just be doing steps 5-7 to connect and communicate.
For more information and sample code, check out the "Discovering Devices" and "Connecting Devices" sections of the Android SDK Bluetooth Guide.
HTH
API level 19 and above you can call createBond() on BluetoothDevice instace to which you want to connect.
You will require some permissions to discover and list the visible devices
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
Code to discover and list the devices:
bluetoothFilter.addAction(BluetoothDevice.ACTION_FOUND);
bluetoothFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
bluetoothFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
registerReceiver(bluetoothReceiver, bluetoothFilter);
private BroadcastReceiver bluetoothReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
Log.e("bluetoothReceiver", "ACTION_FOUND");
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
devicesList.add((device.getName() != null ? device.getName() : device.getAddress()));
bluetoothDevicesAdapter.notifyDataSetChanged();
} else if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) {
Log.e("bluetoothReceiver", "ACTION_DISCOVERY_STARTED");
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
Log.e("bluetoothReceiver", "ACTION_DISCOVERY_FINISHED");
getActivity().unregisterReceiver(bluetoothReceiver);
}
}
};
Just call createBond() on selected device.
How could I programmatically set data roaming on/off in my android application ?
Apologies in advance for reopening a dead post but I have managed to achieve it by calling this executable:
su -c settings put global data_roaming0 1
Also to get the roaming setting for first SIM card:
su -c settings get global data_roaming0
If your app is signatureOrSystem/Privileged app (app resides in /system/priv-app) and your have valid android.permission.WRITE_SECURE_SETTINGS permission in system/etc/permissions. Then you can do it as below.
Enable :
Settings.Global.putInt(context.getContentResolver(), Settings.Global.DATA_ROAMING, 1)
Disable :
Settings.Global.putInt(context.getContentResolver(), Settings.Global.DATA_ROAMING, 0)
I hope that it's not possible to turn on data roaming programmatically as this would be a serious security issue from my point of view ...
Data roaming (i.e. UMTS data transfer via a foreign network) may result in a huge bill from your network provider - at least in europe.
If data roaming is currently on, then I think you can manipulate the Access Points Names in order to make it appear that a data service isn't available. See this post which also links to apndroid. You could browse their source and see the approach they have taken.
If data roaming has been set to off by the user, then this approach won't work. Though you could prompt users to turn it on as part of your install/setup process, which is the route apndroid take.
apndroid also provide an API for changing these kind of settings, which might be more convenient than reimplementing the same functionality.
On rooted devices when using su to enable data roaming, on multi sim devices the data roaming setting is sim specific.
So you need to get the sim number that is active for data calls
sim_num = settings get global multi_sim_data_call
and use this in the data_roaming + sim_num setting. EG sim_num 3
settings get global data_roaming3
if this is null then not multi sim device and use data_roaming otherwise use
settings put global data_roaming3
I was able to enable data roaming on my dual sim Motorola G8 without the need to root it via ADB. I'm posting here the procedure, because the phone has a bug that prevents data roaming from being enabled normally.
You need a computer and to install ADB installed
Enable developer mode and USB debugging in your phone
Connect the phone to the computer via USB and accept the debugging connection.
Start an "adb shell", be sure that it is correctly connected to your phone.
Issue the command
settings put global data_roaming1 1
to enable data roaming for SIM card 1, or
settings put global data_roaming2 1
to enable it for SIM 2
Note: if you do not have the USB cable, this can be done via wifi, but the pairing process is a bit complicated and version dependent.
If you do not have a computer, it may be possible to run the commands directly on the phone using a "local adb" app (there are a few on the play store), but I have not tested any.