For my application I need to make the android device act as the USB Host. It needs to send and receive data from USB connected devices. I have gone through USB Host in Android Developers Site, and developed sample code as follows:
Main.java
public class UsbDemoProjActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button btn = (Button)findViewById(R.id.button1);
btn.setOnClickListener( new OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "button click", 30).show();
Intent it = new Intent(UsbDemoProjActivity.this,Second.class);
startActivity(it);
}
});
}
}
Second.java:
public class Second extends Activity{
UsbDevice device;
UsbManager mUsbManager;
PendingIntent mPermissionIntent;
private static String ACTION_USB_PERMISSION ="com.android.example.USB_PERMISSION";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
System.out.println("111111111");
mUsbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
ACTION_USB_PERMISSION ="com.android.example.USB_PERMISSION";
System.out.println("2222222222");
HashMap<String, UsbDevice> deviceList = mUsbManager.getDeviceList();
device = deviceList.get("deviceName");
System.out.println("33333333333");
mPermissionIntent = PendingIntent.getBroadcast(this, 0,
new Intent(ACTION_USB_PERMISSION), 0);
System.out.println("444444444444");
IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
System.out.println("555555555555");
registerReceiver(mUsbReceiver, filter);
System.out.println("66666666666");
mUsbManager.requestPermission(device, mPermissionIntent);
}
private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
System.out.println("7777777777777");
if (ACTION_USB_PERMISSION.equals(action)) {
synchronized (this) {
System.out.println("88888888888");
UsbDevice device = (UsbDevice)intent.getParcelableExtra(
UsbManager.EXTRA_DEVICE);
if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
if(device != null){
System.out.println("99999999999999");
//call method to set up device communication
}
} else {
//Log.d(TAG, "permission denied for device " + device);
System.out.println("permission denied for device" + device);
}
}
}
}
};
}
However, when I click on button in Main.java page it is showing an error as:
Unfortunately USBDemoProj has been stopped
and in logcat displaying error as per the below image but here the system.output() lines are displaying which are declared in Second.java class. Can anyone please help me what is the error in my app?
Also, am I using the correct method in my sample code to access devices in USB Host Mode? Can anyone suggest me a better way?
I'm using a slickdev library to talk to my serial device, so I'm not sure about your code. It's not onDataReceived()? That might just be the library's function but...
our manifests should both have this in it:
<uses-feature android:name="android.hardware.usb.host" android:required="true"></uses-feature>
and in the
<intent-filter>
<action android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED" />
</intent-filter>
<meta-data android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED"
android:resource="#xml/device_filter" />
Related
How can I use an app to detect when the otg cable is plugged in and when it's not?
Is there an intent for otg cables like the one below for usb devices: "android.hardware.usb.action.USB_DEVICE_ATTACHED"
I have created an app but it only detects a flash drive and not an otg cable:
public class MainActivity extends AppCompatActivity
{
private TextView mInfo;
private Logger mLogger;
private HashMap<UsbDevice, UsbDataBinder> mHashMap = new HashMap<UsbDevice, UsbDataBinder>();
private UsbManager mUsbManager;
private PendingIntent mPermissionIntent;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mInfo = (TextView)findViewById(R.id.log);
mLogger = new Logger(this);
mLogger.setMode(Logger.MODE_TOAST);
mUsbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
usbConnection();
}
private void usbConnection() {
IntentFilter filter = new IntentFilter(UsbManager.ACTION_USB_DEVICE_ATTACHED);
registerReceiver(mUsbAttachReceiver , filter);
filter = new IntentFilter(UsbManager.ACTION_USB_DEVICE_DETACHED);
registerReceiver(mUsbDetachReceiver , filter);
mPermissionIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_USB_PERMISSION), 0);
filter = new IntentFilter(ACTION_USB_PERMISSION);
registerReceiver(mUsbReceiver, filter);
showDevices();
}
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(mUsbDetachReceiver);
unregisterReceiver(mUsbAttachReceiver);
unregisterReceiver(mUsbReceiver);
};
BroadcastReceiver mUsbDetachReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (UsbManager.ACTION_USB_DEVICE_DETACHED.equals(action)) {
UsbDevice device = (UsbDevice)intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
if (device != null) {
// call your method that cleans up and closes communication with the device
UsbDataBinder binder = mHashMap.get(device);
if (binder != null) {
binder.onDestroy();
mHashMap.remove(device);
Toast.makeText(MainActivity.this, "Attached!", Toast.LENGTH_SHORT).show();
}
}
}
}
};
BroadcastReceiver mUsbAttachReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (UsbManager.ACTION_USB_DEVICE_ATTACHED.equals(action)) {
showDevices();
Toast.makeText(MainActivity.this, "Detached!", Toast.LENGTH_SHORT).show();
}
}
};
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) {
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) {
// call method to set up device communication
UsbDataBinder binder = new UsbDataBinder(mUsbManager, device);
mHashMap.put(device, binder);
Toast.makeText(MainActivity.this, "Permission Granted!", Toast.LENGTH_SHORT).show();
}
} else {
// Log.d(TAG, "permission denied for device " + device);
}
}
}
}
};
private void showDevices() {
HashMap<String, UsbDevice> deviceList = mUsbManager.getDeviceList();
Iterator<UsbDevice> deviceIterator = deviceList.values().iterator();
while(deviceIterator.hasNext()){
UsbDevice device = deviceIterator.next();
mUsbManager.requestPermission(device, mPermissionIntent);
//your code
mLogger.log("usb", "name: " + device.getDeviceName() + ", " +
"ID: " + device.getDeviceId());
mInfo.append(device.getDeviceName() + "\n");
mInfo.append(device.getDeviceId() + "\n");
mInfo.append(device.getDeviceProtocol() + "\n");
mInfo.append(device.getProductId() + "\n");
mInfo.append(device.getVendorId() + "\n");
}
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
}
}
I never tried USB OTG, but from https://github.com/shakalaca/USB-OTG-Manager you can use
<intent-filter>
<action android:name="com.sonyericsson.hardware.action.USB_OTG_DEVICE_CONNECTED" />
<action android:name="com.sonyericsson.hardware.action.USB_OTG_DEVICE_DISCONNECTED" />
<action android:name="com.sonyericsson.hardware.action.USB_OTG_ERROR" />
<action android:name="com.sonyericsson.usbotg.ACTION_ERROR_OK" />
<action android:name="android.hardware.usb.action.USB_DEVICE_DETACHED" />
</intent-filter>
From the documentation:
USB OTG Manager
This software is originally designed for Sony Ericsson Xperia Arc S.
Since OTG is enabled in kernel, I'm wondering why I can't access my
memory stick. So I've created this little application for reading
books on my thumb disk, and happily ever after ! :D
Supported Phone:
* Sony Ericsson Xperia Arc S (4.0.2.A.042, 4.0.2.A.062)
* Sony Ericsson Xperia Mini Pro (4.0.2.A.042, 4.0.2.A.058)
* Samsung Galaxy Nexus
Supported USB Device:
* FAT USB memory stick
* Card Reader
related project: https://github.com/mik3y/usb-serial-for-android
you're on your own boat now.
I am developing an application for a Bluetooth client side, and inside this application has a listview that will list out all the connected devices. First, the application will check for the availability of the Bluetooth and then try to connect to another device(Server) , beside that, I initialised the intent filter in the manifest file.
Below is my code :
public class MainActivity extends AppCompatActivity {
ArrayAdapter<String> listAdapter;
ListView listView;
BluetoothAdapter mBluetoothAdapter;
Set<BluetoothDevice> bondedDevices;
private BluetoothSocket socket;
Intent discoverableIntent;
private BluetoothDevice remoteDevice;
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if(intent.getAction().equalsIgnoreCase("android.bluetooth.BluetoothDevice.ACTION_ACL_CONNECTED"))
{
Log.i("Connect", "Connecting.>>>>");
unregisterReceiver(this);
remoteDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
String Temp1 = remoteDevice.getName();
String Temp2 = remoteDevice.getAddress();
listAdapter.add(Temp1 + Temp2);
listView.setAdapter(listAdapter);
new Thread(reader).start();
}
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
IntentFilter intentFilter = new IntentFilter("com.example.jackpowell.bluetoothclient.ACTION_ACL_CONNECTED");
registerReceiver(mReceiver,intentFilter);
startDiscovery();
}
private void startDiscovery() {
mBluetoothAdapter.cancelDiscovery();
mBluetoothAdapter.startDiscovery();
}
public void init() {
listView = (ListView)findViewById(R.id.listView);
listAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,0);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null) {
Toast.makeText(MainActivity.this, "Bluetooth is not supported in this device", Toast.LENGTH_SHORT).show();
finish();
} else {
if (!mBluetoothAdapter.isEnabled()) {
turnOnBluetooth();
}
}
bondedDevices = mBluetoothAdapter.getBondedDevices();
discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
startActivity(discoverableIntent);
}
private Runnable reader = new Runnable() {
#Override
public void run() {
try {
Log.i("Connect","Connecting...........");
android.util.Log.e("TrackingFlow", "Found: " + remoteDevice.getName());
UUID uuid = UUID.fromString("a60f35f0-b93a-11de-8a19-03002011c456");
socket = remoteDevice.createRfcommSocketToServiceRecord(uuid);
socket.connect();
} catch (Exception e) {
e.printStackTrace();
}
}
};
private void turnOnBluetooth() {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, 1);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_CANCELED) {
Toast.makeText(getApplicationContext(), "Bluetooth must be enabled to continue", Toast.LENGTH_SHORT).show();
finish();
}
}
#Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(mReceiver);
}
}
my manifest:
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<receiver android:name="bluetoothclient">
<intent-filter>
<action android:name="android.bluetooth.BluetoothDevice.ACTION_ACL_CONNECTED" />
</intent-filter>
</receiver>
The problem now is onReceive() and registerReceiver() these method never been called, or maybe it already called, I just dont get it. If these method were called, the log cat should be displaying the log command. Why are these method never been called? thank you in advance!
The action name is "android.bluetooth.device.action.ACL_CONNECTED" (to use in manifest) or BluetoothDevice.ACTION_ACL_CONNECTED (to use in code, for intent filter). Action names in your code seem wrong.
Note, to register receiver in manifest the receiver name should be public class based on BroadcastReceiver, not sure what is the "bluetoothclient" meaning in the code above (you didn't show the receiver code).
Usually you don't need both manifest receiver and intent filter receiver in activity, one may be sufficient. The main difference is that manifest receiver can be independent from activity life cycle and receive even when activity is not running.
Try to listen also for ACTION_FOUND (per documentation after startDiscovery you'll receive BluetoothDevice.ACTION_FOUND) and others and try to reduce into minimal example. You need also check result of startDiscovery() which can return false on failure.
Here is slightly modified sample from Discovering devices section:
#Override
protected void onCreate(Bundle savedInstanceState) {
...
// Register for broadcasts
IntentFilter filter = new IntentFilter();
filter.addAction(BluetoothDevice.ACTION_FOUND);
filter.addAction(BluetoothDevice.ACTION_ACL_CONNECTED);
filter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED);
filter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECT_REQUESTED);
registerReceiver(mReceiver, filter);
...
if(!mBluetoothAdapter.startDiscovery()){
Log.e("Bluetooth", "discovery error");
}
}
// Create a BroadcastReceiver for bluetooth actions
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
Log.i("Bluetooth", "got action " + action);
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// Discovery has found a device. Get the BluetoothDevice
// object and its info from the Intent.
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
String deviceName = device.getName();
String deviceHardwareAddress = device.getAddress(); // MAC address
Log.i("Bluetooth", "got device " + deviceName );
}
}
};
#Override
protected void onDestroy() {
super.onDestroy();
...
// Don't forget to unregister the ACTION_FOUND receiver.
unregisterReceiver(mReceiver);
}
Also note, per this question/answer, on some devices discovery does not always work as expected and there is a need for workarounds.
By the way, did you check the logcat for other errors, for example denied permissions etc.? You may try to enable location and add location permission.
Here is a working sample to display all devices:
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.testbluetooth"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="17"
android:targetSdkVersion="21" />
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
MainActivity.java
package com.example.testbluetooth;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.view.ViewGroup.LayoutParams;
import android.widget.FrameLayout;
import android.widget.TextView;
public class MainActivity extends Activity {
TextView textView;
StringBuilder text = new StringBuilder();
private void addLine(String line)
{
Log.i(getClass().getSimpleName(), line);
text.append("[bluetooth] ").append(line).append('\n');
if(textView!=null)
textView.setText(text);
}
BluetoothAdapter mBluetoothAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_main);
FrameLayout content = new FrameLayout(this);
textView = new TextView(this);
content.addView(textView, new FrameLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
addLine("onCreate");
setContentView(content);
// Register for broadcasts
IntentFilter filter = new IntentFilter();
filter.addAction(BluetoothDevice.ACTION_FOUND);
filter.addAction(BluetoothDevice.ACTION_ACL_CONNECTED);
filter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED);
filter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECT_REQUESTED);
registerReceiver(mReceiver, filter);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
for(BluetoothDevice pairedDevice : mBluetoothAdapter.getBondedDevices())
{
addLine("got paired device " + pairedDevice.getName());
}
if(!mBluetoothAdapter.startDiscovery()){
addLine("ERROR: discovery error");
}
else
{
addLine("starting discovery");
}
}
// Create a BroadcastReceiver for bluetooth actions
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
addLine("got action " + action);
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// Discovery has found a device. Get the BluetoothDevice
// object and its info from the Intent.
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
String deviceName = device.getName();
//String deviceHardwareAddress = device.getAddress(); // MAC address
addLine("got device " + deviceName );
}
}
};
}
I am trying to detect USB connection in my app, that is, whether or not USB is connected to device.
It's being tested on Marshmallow 6.0.1 (sdk23)
But I'm unable to receive the broadcast actions ACTION_USB_DEVICE_ATTACHED or ACTION_USB_DEVICE_DETACHED..
I tried using both the dynamic way and the AndroidManifest.xml way, neither worked..
Here's my code:
AndroidManifest.xml :
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.gokulnc.blah_blah"
android:installLocation="auto"
android:versionCode="15"
android:versionName="1.5.1">
<uses-feature android:name="android.hardware.usb.host" />
<uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="23" />
<android:uses-permission android:name="android.permission.USB_PERMISSION" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:vmSafeMode="false">
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:theme="#style/DrawerTheme">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<receiver android:name="mUsbReceiver">
<intent-filter>
<action android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED" />
</intent-filter>
<intent-filter>
<action android:name="android.hardware.usb.action.USB_DEVICE_DETACHED" />
</intent-filter>
</receiver>
</activity>
</application>
</manifest>
MainActivity.java :
public class MainActivity extends AppCompatActivity {
BroadcastReceiver mUsbReceiver;
public void onCreate(Bundle savedInstanceState) {
.....
setBroadcastReceivers();
}
void setBroadcastReceivers() {
//Reference: http://www.codepool.biz/how-to-monitor-usb-events-on-android.html
mUsbReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
Log.d(LOG_TAG, "Received Broadcast: "+action);
if (UsbManager.ACTION_USB_DEVICE_ATTACHED.equals(action) || UsbManager.ACTION_USB_ACCESSORY_ATTACHED.equals(action)) {
updateUSBstatus();
Log.d(LOG_TAG, "USB Connected..");
} else if (UsbManager.ACTION_USB_DEVICE_DETACHED.equals(action) || UsbManager.ACTION_USB_ACCESSORY_DETACHED.equals(action)) {
UsbDevice device = (UsbDevice)intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
if (device != null) {
updateUSBstatus();
}
Log.d(LOG_TAG, "USB Disconnected..");
}
}
};
IntentFilter filter = new IntentFilter();
filter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);
filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
//filter.addAction(UsbManager.ACTION_USB_ACCESSORY_ATTACHED);
//filter.addAction(UsbManager.ACTION_USB_ACCESSORY_DETACHED);
registerReceiver(mUsbReceiver , filter);
Log.d(LOG_TAG, "mUsbReceiver Registered");
}
#Override
public void onResume() {
super.onResume();
Log.d(LOG_TAG, "App Resumed..");
//Refernce: https://stackoverflow.com/questions/18015656/cant-receive-broadcast-intent-of-usbmanager-action-usb-device-attached-usbmanag
Intent intent = getIntent();
if (intent != null) {
if (intent.getAction().equals(UsbManager.ACTION_USB_DEVICE_ATTACHED)) {
Toast.makeText(getApplicationContext(), "Attached", Toast.LENGTH_SHORT).show();
} else if(intent.getAction().equals(UsbManager.ACTION_USB_DEVICE_DETACHED)) {
Toast.makeText(getApplicationContext(), "Detached", Toast.LENGTH_SHORT).show();
}
}
}
}
I also checked this answer: Can't receive broadcast Intent of UsbManager.ACTION_USB_DEVICE_ATTACHED/UsbManager.ACTION_USB_DEVICE_DETACHED, but it didn't help..
Can someone please point out where I'm wrong??
Maybe the reason it doesn't work is that since Android 6.0, the default USB mode is Charging and, maybe ACTION_USB_DEVICE_ATTACHED doesn't get fired up when connected in that mode..
Instead, now I have another solution:
String usbStateChangeAction = "android.hardware.usb.action.USB_STATE";
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
Log.d(LOG_TAG, "Received Broadcast: "+action);
if(action.equalsIgnoreCase(usbStateChangeAction)) { //Check if change in USB state
if(intent.getExtras().getBoolean("connected")) {
// USB was connected
} else {
// USB was disconnected
}
}
}
That is, the broadcast android.hardware.usb.action.USB_STATE is sent whenever there is a toggle in the USB state.
Unlike android.hardware.usb.action.USB_DEVICE_ATTACHED which is broadcasted only when something like a MTP mode is enable, android.hardware.usb.action.USB_STATE is broadcasted whenever it detects an USB connection that's capable of connecting to a host (say computer), irrespective of its current USB Mode like Charging, MTP or whatever.. (it's called USB config to be more precise)
Here the perfect steps to check that external usb connection occur or not in android activity. Just Follow the steps one by one.
In Android Manifest file:
<uses-feature android:name="android.hardware.usb.host" />
<uses-permission android:name="android.permission.USB_PERMISSION" />
Inside your USB checking Activity Tag:
<activity android:name=".USBEnabled">
<intent-filter>
<action android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED" />
</intent-filter>
<meta-data
android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED"
android:resource="#xml/device_filter" />
</activity>
Inside your connectivity checking USBEnabled class :
public class USBEnabled extends AppCompatActivity {
private static final String TAG = "UsbHost";
TextView mDeviceText;
Button mConnectButton;
UsbManager mUsbManager;
UsbDevice mDevice;
PendingIntent mPermissionIntent;
private static final int REQUEST_TYPE = 0x80;
private static final int REQUEST = 0x06;
private static final int REQ_VALUE = 0x200;
private static final int REQ_INDEX = 0x00;
private static final int LENGTH = 64;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_usbenabled);
mDeviceText = (TextView) findViewById(R.id.text_status);
mConnectButton = (Button) findViewById(R.id.button_connect);
mUsbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
}
#Override
protected void onRestart() {
super.onRestart();
recreate();
}
#Override
protected void onResume() {
super.onResume();
mPermissionIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_USB_PERMISSION), 0);
IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
registerReceiver(mUsbReceiver, filter);
updateDeviceList();
}
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(mUsbReceiver);
}
public void onConnectClick(View v) {
if (mDevice == null) {
return;
}
mUsbManager.requestPermission(mDevice, mPermissionIntent);
}
private static final String ACTION_USB_PERMISSION = "com.android.recipes.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)) {
UsbDevice device = (UsbDevice) intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)
&& device != null) {
getDeviceStatus(device);
} else {
Log.d(TAG, "permission denied for device " + device);
}
}
}
};
private void getDeviceStatus(UsbDevice device) {
UsbDeviceConnection connection = mUsbManager.openDevice(device);
byte[] buffer = new byte[LENGTH];
connection.controlTransfer(REQUEST_TYPE, REQUEST, REQ_VALUE, REQ_INDEX,
buffer, LENGTH, 2000);
connection.close();
}
private void updateDeviceList() {
HashMap<String, UsbDevice> connectedDevices = mUsbManager
.getDeviceList();
if (connectedDevices.isEmpty()) {
mDevice = null;
mDeviceText.setText("No Devices Currently Connected");
mConnectButton.setEnabled(false);
} else {
for (UsbDevice device : connectedDevices.values()) {
mDevice = device;
}
mDeviceText.setText("USB Device connected");
mConnectButton.setEnabled(true);
}
}}
Inside your class xml file :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:id="#+id/button_connect"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="onConnectClick"
android:text="Connect" />
<TextView
android:id="#+id/text_status"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="22dp" />
<TextView
android:id="#+id/text_data"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="22dp" />
</LinearLayout>
Now create a new resource directory called xml and create new xml file called device_filter.xml with the following code.
<?xml version="1.0" encoding="utf-8"?>
<resources>
<usb-device />
</resources>
Debug and run the application, it will show external usb device connectivity status without any error. I hope you will get output for your scenario.
Enjoy!!
I've searched and tried everything I could, but I just can't get this to work. From all the examples I've seen, I seem to be doing the right thing, but maybe I'm missing something.
I'm trying to discover Bluetooth devices on Android and have been following the guide on the Android Developer page: http://developer.android.com/guide/topics/connectivity/bluetooth.html
I can enable BT when the app starts and get the name and address of my device. However, I can't see the names of other nearby devices (supposed to show up as a toast). The intriguing part is, when I enable BT before starting the app, it actually does what I want and shows the nearby devices' name.
Here's the code:
public class MainActivity extends AppCompatActivity {
TextView mTextView;
BluetoothAdapter mBluetoothAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
final String status;
// Check BT support
if (mBluetoothAdapter == null){
// Device does not support BT
status = "Your device does not support Bluetooth";
}
else {
String myAddress = mBluetoothAdapter.getAddress();
String myName = mBluetoothAdapter.getName();
status = myName + ": " + myAddress;
}
mTextView = (TextView)findViewById(R.id.textView);
// If BT is enabled before app start, discover devices
// This is where things work, for some reason
if (mBluetoothAdapter.isEnabled()){
mTextView.setText(status);
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mBroadcastReceiver, filter);
getBTdevices();
}
// If BT is not enabled, enable it and look for devices
else{
mTextView.setText(status);
mBluetoothAdapter.enable();
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mBroadcastReceiver, filter);
getBTdevices();
}
}
protected void getBTdevices(){
// Stop discovery and start
if (mBluetoothAdapter.isDiscovering()){
mBluetoothAdapter.cancelDiscovery();
}
mBluetoothAdapter.startDiscovery();
}
private final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
TextView textView = (TextView)findViewById(R.id.textView2);
textView.setText("Start");
String action = intent.getAction();
// If device is found
if (BluetoothDevice.ACTION_FOUND.equals(action)){
// Get BT device from intent
textView.setText("Device found");
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
Toast.makeText(context, "Device found: "+ device.getName(), Toast.LENGTH_LONG).show();
System.out.println("Discovered!");
}
}
};
protected void onDestroy(){
super.onDestroy();
if (mBluetoothAdapter.isDiscovering()){
mBluetoothAdapter.cancelDiscovery();
}
unregisterReceiver(mBroadcastReceiver);
}
}
Some help would really be appreciated, I don't know what else I can do.
EDIT: Forgot to mention, I have set both the BLUETOOTH and BLUETOOTH_ADMIN permissions in the manifest.
I am trying to transfer file to a wifi hotspot host android device from another android device ,like SHAREIT does .
I don't have any clue about that. Though I tried via wifi peer to peer (P2P) method
http://developer.android.com/guide/topics/connectivity/wifip2p.html
I also tried sample code of p2p file transfer which comes with android SDK .
But the main problem is , p2p must needs a wifi access point . So I have created a wifi hotspot using another android device . I have connected the testing device to that hotspot network . But testing device could not find the hotspot host device . Therefore I was unable to transfer file . If I add another device to that network then testing device could find the newly connected device , but not host device , though I need to transfer file to host device .
EDIT
I tried this code
final TextView deviceListText = (TextView) findViewById(R.id.list);
final WifiP2pManager wifiP2pManager = (WifiP2pManager) getSystemService(Context.WIFI_P2P_SERVICE);
channel = wifiP2pManager.initialize(this, getMainLooper(), channelListener);
// wifiP2pManager.discoverPeers(channel, newActionListener);
// wifiP2pManager.createGroup(channel, newActionListener);
final WiFiDirectBroadcastReceiver wiFiDirectBroadcastReceiver = new WiFiDirectBroadcastReceiver(wifiP2pManager, channel, this);
mIntentFilter = new IntentFilter();
mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION);
mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION);
mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION);
mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION);
final Button stop = (Button) findViewById(R.id.button);
final Button start = (Button) findViewById(R.id.button2);
start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
wifiP2pManager.discoverPeers(channel, new WifiP2pManager.ActionListener() {
#Override
public void onSuccess() {
deviceListText.setText(" discovering peers ");
}
#Override
public void onFailure(int reason) {
deviceListText.setText("error discovering peers "+String.valueOf(reason));
}
});
}
});
myPeerListListener = new WifiP2pManager.PeerListListener()
{
#Override
public void onPeersAvailable(final WifiP2pDeviceList peers) {
Collection<WifiP2pDevice> devicesAddressObj = peers.getDeviceList();
for (final WifiP2pDevice newDevice : devicesAddressObj) {
// deviceListText.setText(newDevice.deviceName);
config.deviceAddress = newDevice.deviceAddress;
wifiP2pManager.connect(channel, config, new WifiP2pManager.ActionListener() {
#Override
public void onSuccess() {
deviceListText.setText(" connected ");
}
#Override
public void onFailure(int reason) {
deviceListText.setText(" not connect , reason: " + String.valueOf(reason));
}
});
}
}
};
*This is my broadcast receiver *
public class WiFiDirectBroadcastReceiver extends BroadcastReceiver {
private WifiP2pManager mManager;
private WifiManager wifiManager2;
private WifiP2pManager.Channel mChannel;
private Activity mActivity;
final TextView deviceListText = (TextView) findViewById(R.id.list);
public WiFiDirectBroadcastReceiver(WifiP2pManager manager, WifiP2pManager.Channel channel,
Activity activity) {
super();
this.mManager = manager;
this.mChannel = channel;
this.mActivity = activity;
}
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
StringBuilder stringBuilder = new StringBuilder();
if (WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION.equals(action)) {
// Check to see if Wi-Fi is enabled and notify appropriate activity
} else if (WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION.equals(action)) {
// Call WifiP2pManager.requestPeers() to get a list of current peers
if (mManager != null) {
mManager.requestPeers(mChannel, myPeerListListener);
}
} else if (WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION.equals(action)) {
// Respond to new connection or disconnections
} else if (WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION.equals(action)) {
// Respond to this device's wifi state changing
runOnUiThread(new Runnable() {
#Override
public void run() {
deviceListText.setText("device's wifi state changing");
}
});
}
}
}
Any help would be appreciated .