I'm new to android app. I want to read data from my arduino Uno R3 and display it on my app using a serial cable and an OTG adapter.
Although, I can't get my UsbManager to recognized my device. So when I try to set up a connection, it always fail.
Here's the part of my code where I initiate everything.
public UsbManager = mUsbManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_depth);
setupActionBar();
textView = (TextView) findViewById(R.id.textView2);
mUsbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
button = (Button) findViewById(R.id.buttonStart);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
textView.setText("Bravo");
updateDevice();
if (mRunning == true) {
receiveThread();
}
}
});
}
public void updateDevice() {
Intent intent= getIntent();
String action = intent.getAction();
UsbDevice device = (UsbDevice) intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
if (device != null){
Toast.makeText(this, "Initialisation 1", Toast.LENGTH_SHORT).show();
initDevice(device);
}
if (UsbManager.ACTION_USB_DEVICE_ATTACHED.equals(action)) {
Toast.makeText(this, "Initialisation", Toast.LENGTH_SHORT).show();
initDevice(device);
} else {
initDevice(null);
}
}
(...) //Obviously, this is not in my code!!
private boolean initDevice(UsbDevice device) {
mConnection = mUsbManager.openDevice(device);
if (mConnection == null) {
if (DEBUG) Log.e(TAG, "Opening USB device failed!");
Toast.makeText(DisplayDepth.this, "open failed", Toast.LENGTH_SHORT).show();
return false;
}
And it always fail here ( I get the toast msg "open failed" ).
I add to my manifest what it takes so my arduino r3 is recognized and a connection message is always shown when I plug it into my phone.... Need help!!!
Thanks
Related
The discovery and pairing process described in the Android Bluetooth Documentation is quite complex. Even a separate permission is needed for that: BLUETOOTH_ADMIN.
I wonder if there is a system action, that I just would call, that will handle the UI, return, and the I will just choose an already paired device. Or do I have to implement all that UI myself?
if you want to get the list of paired bluetooth devices you can use this code
public class DeviceList extends ActionBarActivity
{
//widgets
Button btnPaired;
ListView devicelist;
//Bluetooth
private BluetoothAdapter myBluetooth = null;
private Set<BluetoothDevice> pairedDevices;
public static String EXTRA_ADDRESS = "device_address";
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_device_list);
//Calling widgets
btnPaired = (Button)findViewById(R.id.button);
devicelist = (ListView)findViewById(R.id.listView);
//if the device has bluetooth
myBluetooth = BluetoothAdapter.getDefaultAdapter();
if(myBluetooth == null)
{
//Show a mensag. that the device has no bluetooth adapter
Toast.makeText(getApplicationContext(), "Bluetooth Device Not Available", Toast.LENGTH_LONG).show();
//finish apk
finish();
}
else if(!myBluetooth.isEnabled())
{
//Ask to the user turn the bluetooth on
Intent turnBTon = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(turnBTon,1);
}
btnPaired.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
pairedDevicesList();
}
});
}
private void pairedDevicesList()
{
pairedDevices = myBluetooth.getBondedDevices();
ArrayList list = new ArrayList();
if (pairedDevices.size()>0)
{
for(BluetoothDevice bt : pairedDevices)
{
list.add(bt.getName() + "\n" + bt.getAddress()); //Get the device's name and the address
}
}
else
{
Toast.makeText(getApplicationContext(), "No Paired Bluetooth Devices Found.", Toast.LENGTH_LONG).show();
}
final ArrayAdapter adapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1, list);
devicelist.setAdapter(adapter);
devicelist.setOnItemClickListener(myListClickListener); //Method called when the device from the list is clicked
}
private AdapterView.OnItemClickListener myListClickListener = new AdapterView.OnItemClickListener()
{
public void onItemClick (AdapterView<?> av, View v, int arg2, long arg3)
{
// Get the device MAC address, the last 17 chars in the View
String info = ((TextView) v).getText().toString();
String address = info.substring(info.length() - 17);
// Make an intent to start next activity.
Intent i = new Intent(DeviceList.this, NextActivity.class);
//Change the activity.
i.putExtra(EXTRA_ADDRESS, address); //this will be received at NextActivity
startActivity(i);
}
};
}
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 working on a Bluetooth control App using Android , when the user click the Pair button to start the connection with another Bluetooth device , i want to open another activity after amount of time ( when the pairing between the two devices is finished) .
The problem is that the App is stopped after pairing between devices . what is the problem in my code ? i have searched a lot but i havent found any solution .Please any help would be appreciated .
thanks in advance
this is my code
public class DevicesListActivity extends Activity
{
private ListView mListView;
private DeviceListAdapter mAdapter;
//the List that we will receive from the Main Activity
private ArrayList<BluetoothDevice> PassedDeviceList;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_devices_list);
PassedDeviceList = getIntent().getExtras().getParcelableArrayList("device.list");
mListView = (ListView) findViewById(R.id.DevicesList_lv);
mAdapter = new DeviceListAdapter(this);
mAdapter.setData(PassedDeviceList);
mAdapter.setListener(new DeviceListAdapter.OnPairButtonClickListener() {
#Override
public void onPairButtonClick(int position)
{
showToast("PairedBTN Clicked");
BluetoothDevice device = PassedDeviceList.get(position);
if (device.getBondState() == BluetoothDevice.BOND_BONDED)
{
unpairDevice(device);
}
else
{
showToast("Pairing...");
pairDevice(device);
}
}
});
mListView.setAdapter(mAdapter);
registerReceiver(mPairReceiver, new IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED));
}
//***** We will Pair with the Selected Device then Go to the Control Screen
private void pairDevice(final BluetoothDevice device)
{
try
{
Method method = device.getClass().getMethod("createBond", (Class[]) null);
method.invoke(device, (Object[]) null);
showToast("YOu have Paired with Device Name:" + device.getName()+" And Address: " + device.getAddress() );
//***** Make an intent to start next activity.*****
new Handler().postDelayed(new Runnable() {
public void run() {
Intent i = new Intent(DevicesListActivity.this, MobileControl.class);
//Change the activity.
String address = device.getAddress();
i.putExtra("ADDRESS", address); //this will be received at Control Activity
startActivity(i);
//finish();
}
}, 10000);
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
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 .
I enable wi-fi tethering through my application in my android device. How do I get notification in my application when someone connects to the Wi-Fi network tethered by my application? Do I need to register for some specific broadcast receivers?
I have pasted below the application source code
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
((ToggleButton) findViewById(R.id.toggle_tethering)).setOnCheckedChangeListener(this);
}
#Override
public void onCheckedChanged(CompoundButton button, boolean isChecked) {
WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE);
Boolean result = false;
WifiConfiguration config = new WifiConfiguration();
config.SSID = "Tab3OpenWifi";
config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
String setWifiApConfigurationMethodName = "setWifiApConfiguration";
Method setWifiApConfigurationMethod = wifiManager.getClass().getMethod(setWifiApConfigurationMethodName, WifiConfiguration.class);
result = (Boolean) setWifiApConfigurationMethod.invoke(wifiManager, config);
if (result) {
String setWifiApEnableMethodName = "setWifiApEnabled";
Method setWifiApEnableMethod = wifiManager.getClass().getMethod(setWifiApEnableMethodName, WifiConfiguration.class, boolean.class);
String message;
if (isChecked) {
result = (Boolean) setWifiApEnableMethod.invoke(wifiManager, null, true);
if (result) {
message = "Enabling tethering successfully";
} else {
message = "Enabling tethering failed";
}
} else {
result = (Boolean) setWifiApEnableMethod.invoke(wifiManager, null, false);
if (result) {
message = "Disabling tethering successfully";
} else {
message = "Disabling tethering failed";
}
}
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Failed to update Wifi Tethering config.", Toast.LENGTH_SHORT).show();
}
}
I used below broadcast receiver to get the AP state.
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Log.d(TAG,"mReceiver.onReceive>>");
String action = intent.getAction();
if (WIFI_AP_STATE_CHANGED_ACTION.equals(action)) {
Log.d(TAG,"WIFI_AP_STATE_CHANGED_ACTION");
} else if (ACTION_TETHER_STATE_CHANGED.equals(action)) {
ArrayList<String> available = intent.getStringArrayListExtra(
EXTRA_AVAILABLE_TETHER);
ArrayList<String> active = intent.getStringArrayListExtra(
EXTRA_ACTIVE_TETHER);
ArrayList<String> errored = intent.getStringArrayListExtra(
EXTRA_ERRORED_TETHER);
Log.d(TAG,"==Available==");
for(String str : available)
Log.d(TAG, ""+str);
Log.d(TAG,"==Active==");
for(String str : active)
Log.d(TAG, ""+active);
Log.d(TAG,"==Error==");
for(String str : errored)
Log.d(TAG, ""+str);
} else if (Intent.ACTION_AIRPLANE_MODE_CHANGED.equals(action)) {
}
Log.d(TAG,"mReceiver.onReceive<<");
}
};
I don't think there is an API for that, nor any broadcast event which you can listen to.
The only option that I can think of is operating at a lower level, i.e. the kernel level. I am no expert, but I used to monitor the /proc/net/tcp file to look for open connections. That may be a starting point for you.
I also wrote a simple library, if you want to get a glimpse of how I did it. You can find it here: https://github.com/dextorer/AndroidTCPSourceApp