Get Bluetooth device information from the Android bluetooth device picker - java

I am developing an Android application which involves showing the user a list of nearby Bluetooth devices and connecting to the device selected by them. I'm trying to use the system bluetooth device picker as shown in these posts:
How to retrieve Bluetooth device info with Android Bluetooth device picker?
Android Bluetooth Device Picker Usage
The device picker does show, but I can't find out which device was selected in my code. The toast inside the onReceive does not show, which suggests that no broadcast is being received.
Another problem I faced is that if I try to start the device picker activity inside the onRequestPermissionsResult, the device picker does not show up at all, despite clicking 'allow' in the request permission dialog. The toast inside doesn't get displayed either.
Here's the code:
//Code inside Fragment
BroadcastReceiver mReceiver;
BluetoothAdapter bluetoothAdapter;
BluetoothSocket bsock;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
myView = inflater.inflate(R.layout.controller_mode_layout,container,false);
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
//Get location access permission.
if (bluetoothAdapter != null) {
if (bluetoothAdapter.isEnabled()) {
ActivityCompat.requestPermissions(getActivity(),new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, reqCode);
}
}
//Receiver to get the selected device information
mReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
context.unregisterReceiver(this);
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
Toast.makeText(context,"Device"+device.getAddress(), Toast.LENGTH_SHORT).show();
try {
bsock=device.createRfcommSocketToServiceRecord(UUID.fromString("00002415-0000-1000-8000-00805F9B34FB"));
bsock.connect();
//Send and receive data logic follows
} catch (IOException e) {
e.printStackTrace();
}
}
};
getActivity().registerReceiver(mReceiver, new IntentFilter("android.bluetooth.devicepicker.action.DEVICE_SELECTED"));
showDevicePicker();
return myView;
}
#Override
public void onRequestPermissionsResult (int requestCode, String[] permissions, int[] grantResults)
{
Toast.makeText(getActivity(),"Permission result", Toast.LENGTH_SHORT).show();
if((requestCode == reqCode) && (grantResults[0] == PackageManager.PERMISSION_GRANTED))
{
//Not working
// showDevicePicker();
}
}
public void showDevicePicker()
{
//Launch built in bluetooth device picker activity
startActivity( new Intent("android.bluetooth.devicepicker.action.LAUNCH")
.putExtra("android.bluetooth.devicepicker.extra.NEED_AUTH", false)
.putExtra("android.bluetooth.devicepicker.extra.FILTER_TYPE", 0)
.putExtra("android.bluetooth.devicepicker.extra.LAUNCH_PACKAGE","com.example.ankit2.controllerapp1")
.putExtra("android.bluetooth.devicepicker.extra.DEVICE_PICKER_LAUNCH_CLASS","com.example.ankit2.controllerapp1.Fragment1")
.setFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS));
}
Any help will be appreciated.
Note: I tested the code on a Lenovo K3 note running Marshmallow.

The problem was in the DEVICE_PICKER_LAUNCH_CLASS, which was specified as Fragment1. The launch class must be an activity, even if the broadcast receiver is inside a fragment. In this case, changing the launch class to ControllerActivity (which contains the fragment Fragment1) fixed the problem.

Related

Android bluetooth scan errors

btAdapter.isDiscovering(),btAdapter.startDiscovery(); btAdapter.cancelDiscovery(); device.getName();
4four erros
Call requires permission which may be rejected by user: code should explicitly check to see if permission is available (with checkPermission) or explicitly handle a potential SecurityException
Please solve this problem
public void onClickButtonSearch(View view){
// Check if the device is already discovering
if(btAdapter.*isDiscovering()*){
*btAdapter.cancelDiscovery()*;
} else {
if (btAdapter.isEnabled()) {
*btAdapter.startDiscovery();*
btArrayAdapter.clear();
if (deviceAddressArray != null && !deviceAddressArray.isEmpty()) {
deviceAddressArray.clear();
}
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(receiver, filter);
} else {
Toast.makeText(getApplicationContext(), "bluetooth not on", Toast.LENGTH_SHORT).show();
}
}
}
// Create a BroadcastReceiver for ACTION_FOUND.
private final BroadcastReceiver receiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
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
btArrayAdapter.add(deviceName);
deviceAddressArray.add(deviceHardwareAddress);
btArrayAdapter.notifyDataSetChanged();
}
}
};
protected void onDestroy() {
super.onDestroy();
// Don't forget to unregister the ACTION_FOUND receiver.
unregisterReceiver(receiver);
}
For apps targeting Android 11 or lower, calling BluetoothAdapter#startDiscovery() requires the Manifest.permission#BLUETOOTH_ADMIN permission which can be gained with a simple manifest tag.
For apps targeting API Level 31 or higher, this requires the Manifest.permission#BLUETOOTH_SCAN permission.
In addition, this requires either the Manifest.permission#ACCESS_FINE_LOCATION permission or a strong assertion that you will never derive the physical location of the device.
A permission can be gained with the following code:
getActivity().requestPermissions(new String[]{ Manifest.permission.ACCESS_FINE_LOCATION},
YOUR_REQUEST_LOCATION_PERMISSION_CODE);
For more infos: https://developer.android.com/reference/android/bluetooth/BluetoothAdapter#startDiscovery()

Bluetooth OnReceive Method Doesn't Get Called

I'm trying to make an android app which has some issues about Bluetooth. I simply enable Bluetooth, find devices, connect one of the devices, send & receive data. First thing is done. But in second, there are some problems. I make a Broadcast Receiver to discover devices nearby my phone. But OnReceive method doesn't get called. The weird thing is, it was getting called at first and I was able to see devices nearby. Then something that I cannot figure out happened and now OnReceive method doesn't get called. I've searched topics about these but none of them could solve my problem. MyDevice and MyAdapter are my own classes to show Bluetooth devices in listview with my own layout. Here is my code:
public class FoundDevicesActivity extends AppCompatActivity {
BluetoothAdapter bluetoothAdapter;
ListView foundedDevicesListView;
MyDeviceAdapter deviceAdapter;
List<MyDevice> foundedDevicesList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_found_devices);
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
foundedDevicesListView = (ListView) findViewById(R.id.foundDevicesListview);
if (bluetoothAdapter.isDiscovering()) {
bluetoothAdapter.cancelDiscovery();
}
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
filter.addAction(BluetoothDevice.ACTION_FOUND);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
this.registerReceiver(receiver, filter);
bluetoothAdapter.startDiscovery();
deviceAdapter = new MyDeviceAdapter(this, foundedDevicesList);
foundedDevicesListView.setAdapter(deviceAdapter);
}
private final BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) {
Toast.makeText(FoundDevicesActivity.this, "Discovery is started !!", Toast.LENGTH_SHORT).show();
Log.d("Found Devices Activity", "Discovery is started !!");
} else if (BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
MyDevice dvc = new MyDevice();
if (device.getName().equals(null)) {
dvc.name = "UNDEFINED NAME";
} else {
dvc.name = device.getName();
}
if(device.getAddress().equals(null)) {
dvc.address = "UNDEFINED ADDRESS";
} else {
dvc.address = device.getAddress();
}
foundedDevicesList.add(dvc);
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
bluetoothAdapter.cancelDiscovery();
Toast.makeText(FoundDevicesActivity.this, "Discovery is finished !!", Toast.LENGTH_SHORT).show();
Log.d("Found Devices Activity", "Discovery is finished !!");
}
}
};
}
Any idea ?

Android: Broadcast Receiver does not receive BluetoothDevice.ACTION_ACL_CONNECTED on restarting the application

I want my app to auto-connect to already connected bluetooth device on restarting the app. Below is procedure I am performing:-
[Initially] Bluetooth device is 'ON': Then on starting the app.
[Behavior]--> Bluetooth device gets paired and connected successfully ( Intent 'ACTION_ACL_CONNECTED' is received)
Bluetooth device is 'ON': Closed the app, then started the app again.
[Behavior]--> Even though it is connected as displayed on Bluetooth setting, and Broadcast Receiver does not receive Intent 'ACTION_ACL_CONNECTED'.
Note:- On closing the app, it does not disconnect the bluetooth connection.
So, on successful connection app straightaway goes to the HomeScreen. Otherwise, the app goes to a screen having button that takes it to Bluetooth setting(onClickListener present in the code below)
I am new to android development, so I really don't know where am I going wrong. I looked up the solutions for similar issues and applied them, but to no effect.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_index);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_ACL_CONNECTED);
registerReceiver(mReceiver, filter);
IntentFilter filter1 = new IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECTED);
this.registerReceiver(mReceiver, filter1);
m_app = (BtApp) getApplication();
imagebt = (ImageView) this.findViewById(R.id.imagebt);
imagebt.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
final Toast tag = Toast.makeText(getApplicationContext(), "Connect to device", Toast.LENGTH_LONG);
tag.show();
new CountDownTimer(1000, 1000)
{
public void onTick(long millisUntilFinished) {tag.show();}
public void onFinish() {
//tag.show();
}
}.start();
if(mBluetoothAdapter != null && mBluetoothAdapter.isEnabled()){
mBluetoothAdapter.startDiscovery();
}
Intent intentBluetooth = new Intent();
intentBluetooth.setAction(android.provider.Settings.ACTION_BLUETOOTH_SETTINGS);
startActivity(intentBluetooth);
}
});
}
private BroadcastReceiver mReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if ( BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)) {
m_app.m_main.setupCommPort();
device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
m_app.m_device = device;
isconnected = true;
new Timer().schedule(new TimerTask() {
#Override
public void run() {
if ( m_app.m_main.m_BtService != null && m_app.m_main.m_BtService.getState() != BluetoothRFCommService.STATE_CONNECTED ) {
m_app.m_main.m_BtService.connect(device, false);
}
}
}, 3500);
} else if ( BluetoothDevice.ACTION_ACL_DISCONNECTED.equals(action) ) {
isconnected = false;
m_app.m_main.tabHost.setCurrentTab(0);
}
}
};
#Override
protected void onStop()
{
unregisterReceiver(mReceiver);
super.onStop();
}
You won't get BluetoothDevice.ACTION_ACL_CONNECTED event since the device is still connected. The event is fired only on changing of device state from disconnected to connected.
You have 2 options.
You can put your BroadcastReceiver with BluetoothDevice.ACTION_ACL_CONNECTED and BluetoothDevice.ACTION_ACL_DISCONNECTED filters into the Service and track the device connection state in the background. On your app startup you can ask the service to give you the current state of the device.
You can check if some of the Bluetooth profiles contains your device name in the list of connected devices.
For API 18+ you can use BluetoothManager#getConnectedDevices() for API below 18 you can use the following snippet (for each Bluetooth profile)
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
BluetoothProfile.ServiceListener mProfileListener = new BluetoothProfile.ServiceListener() {
public void onServiceConnected(int profile, BluetoothProfile proxy) {
for (BluetoothDevice device : proxy.getConnectedDevices()) {
if (device.getName().contains("DEVICE_NAME")) {
deviceConnected = true;
}
}
if (!deviceConnected) {
Toast.makeText(getActivity(), "DEVICE NOT CONNECTED", Toast.LENGTH_SHORT).show();
}
mBluetoothAdapter.closeProfileProxy(profile, proxy);
}
public void onServiceDisconnected(int profile) {
// TODO
}
};
mBluetoothAdapter.getProfileProxy(context, mProfileListener, BluetoothProfile.A2DP);

Android: Error in discovering bluetooth devices

I need some help in my Android application. I am trying to create an app that discovers bluetooth devices then compare the name to a string.
but I encountered 2 problems.
1: when I exit the app (back button) it exits then show me a crash message (after few seconds) .. I think the problem is with "mReceiver" (check "2nd problem).
2:(main problem) In the code bellow, the $"mReceiver = new BroadcastReceiver()" part has a problem. I have thrown multiple toasts every where just to check which part doesn't work, everything before this line works fine.
I'm not sure but I think the problem with not having "final" in declaring "mReciver" in the beginning --> "private BroadcastReceiver mReceiver;". However adding final causes problems.
The Code:
public class MainActivity extends Activity {
private final static int REQUEST_ENABLE_BT = 1; //It's really just a number that you provide for onActivityResult (>0)
//Temp objects for testing
private String StringMeeting = "meeting";
ProgressBar bar;
//Member fields
private BluetoothAdapter mBluetoothAdapter;
private ArrayAdapter<String> mPairedDevicesArrayAdapter;
private ArrayAdapter<String> mNewDevicesArrayAdapter;
// Create a BroadcastReceiver for ACTION_FOUND
private BroadcastReceiver mReceiver;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//declare & start progress bar
bar = (ProgressBar) findViewById(R.id.progressBar1);
bar.setVisibility(View.VISIBLE);
//------------Setup a Bluetooth (Get Adapter) ------------------
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null) {
// Device does not support Bluetooth
Toast.makeText(getApplicationContext(), "This Device does not support Bluetooth", Toast.LENGTH_LONG).show();
}else{Toast.makeText(getApplicationContext(), "Getting the Adabter is done", Toast.LENGTH_SHORT).show();}
//------------Setup a Bluetooth (Enable Bluetooth) ------------------
if (!mBluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}else{Toast.makeText(getApplicationContext(), "Enable Bluetooth is done", Toast.LENGTH_SHORT).show();}
//------------Finding Devices (Discovering Devices)----------------------
// Create a BroadcastReceiver for ACTION_FOUND
Toast.makeText(getApplicationContext(), "creating the mReceiver", Toast.LENGTH_SHORT).show(); //last thing works
mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
Toast.makeText(getApplicationContext(), "accessed onReceive + will create action", Toast.LENGTH_SHORT).show();
String action = intent.getAction();
Toast.makeText(getApplicationContext(), "Waiting to discover a device", Toast.LENGTH_SHORT).show();
// When discovery finds a device
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
Toast.makeText(getApplicationContext(), "enterd the if", Toast.LENGTH_SHORT).show();
// Get the BluetoothDevice object from the Intent
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
Toast.makeText(getApplicationContext(), "Getting device names", Toast.LENGTH_SHORT).show();
Toast.makeText(getApplicationContext(), device.getName(), Toast.LENGTH_LONG).show();
Toast.makeText(getApplicationContext(), "displaying the name should be done", Toast.LENGTH_SHORT).show();
// Add the name and address to an array adapter to show in a ListView
mNewDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());
}else{Toast.makeText(getApplicationContext(), "Error: BluetoothDevice.ACTION_FOUND.equals(action) = False", Toast.LENGTH_SHORT).show();}
}
};
// Register the BroadcastReceiver
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mReceiver, filter); // Don't forget to unregister during onDestroy
} //onCreate end
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
// Make sure we're not doing discovery anymore
if (mBluetoothAdapter != null) {
mBluetoothAdapter.cancelDiscovery();
}
// Unregister broadcast listeners
this.unregisterReceiver(mReceiver);
}
}
Thank You For Your Time.
You start an activity for result in order for the user to be prompted whether the user allows Bluetooth to be enabled or not, but you don't wait for the result and try to find devices right away.
You should implement onActivityResult call back. If the result is RESULT_OK, then you start discovering devices. Enabling bluetooth takes some time.

Scanning available wifi, detect specific strongest Wifi SSID to launch an XML activity layout

I need to locate my current location in a building by scanning the strongest available Wifi to launch an activity. I want to locate only 3 places in that building. So if I am currently near any of those locations, I will click a button to scan the strongest available Wifi to launch an activity.
I need to scan available Wifi in a building.
Get the 3 strongest signal.
Then detect whether any of those 3 strongest signal's SSID is the same with the specific SSID that I want to locate.
If my SSID is one of the strongest 3 signals, then the application will launch a xml layout activity,
So far I already have the coding to scan strongest available Wifi. But I don't know how to launch an activity when the strongest specific Wifi SSID detected. I do not need the information about the Wifi, just to launch my activity layout that has my information.
At the moment I'm using the following bit of code to scan the strongest Wifi signal that I got from here:
WiFiDemo.java
public class WiFiDemo extends Activity implements OnClickListener {
private static final String TAG = "WiFiDemo";
WifiManager wifi;
BroadcastReceiver receiver;
TextView textStatus;
Button buttonScan;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Setup UI
textStatus = (TextView) findViewById(R.id.textStatus);
buttonScan = (Button) findViewById(R.id.buttonScan);
buttonScan.setOnClickListener(this);
// Setup WiFi
wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
// Get WiFi status
WifiInfo info = wifi.getConnectionInfo();
textStatus.append("\n\nWiFi Status: " + info.toString());
// List available networks
List<WifiConfiguration> configs = wifi.getConfiguredNetworks();
for (WifiConfiguration config : configs) {
textStatus.append("\n\n" + config.toString());
}
// Register Broadcast Receiver
if (receiver == null)
receiver = new WiFiScanReceiver(this);
registerReceiver(receiver, new IntentFilter(
WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
Log.d(TAG, "onCreate()");
}
#Override
public void onStop() {
unregisterReceiver(receiver);
}
public void onClick(View view) {
Toast.makeText(this, "On Click Clicked. Toast to that!!!",
Toast.LENGTH_LONG).show();
if (view.getId() == R.id.buttonScan) {
Log.d(TAG, "onClick() wifi.startScan()");
wifi.startScan();
}
} }
WiFiScanReceiver.java
public class WiFiScanReceiver extends BroadcastReceiver {
private static final String TAG = "WiFiScanReceiver";
WiFiDemo wifiDemo;
public WiFiScanReceiver(WiFiDemo wifiDemo) {
super();
this.wifiDemo = wifiDemo;
}
#Override
public void onReceive(Context c, Intent intent) {
List<ScanResult> results = wifiDemo.wifi.getScanResults();
ScanResult bestSignal = null;
for (ScanResult result : results) {
if (bestSignal == null
|| WifiManager.compareSignalLevel(bestSignal.level, result.level) < 0)
bestSignal = result;
}
String message = String.format("%s networks found. %s is the strongest.",
results.size(), bestSignal.SSID);
Toast.makeText(wifiDemo, message, Toast.LENGTH_LONG).show();
Log.d(TAG, "onReceive() message: " + message);
}
}
You just need to start your activity from onReceive. Unless I'm not understanding your question, you just need to fire off your activity.
Since you have the context on your receiver's onReceive you just need to startActivity()
Start Activity inside onReceive BroadcastReceiver
#Override
public void onReceive(Context context, Intent intent) {
//start activity
Intent i = new Intent();
i.setClassName("com.test", "com.test.MainActivity");
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
}
Don't forget to define a proper filter for it in your manifest.
http://developer.android.com/reference/android/content/BroadcastReceiver.html

Categories

Resources