-1

Hey guys I am working on an app which should connect to bluetooth devices. But at the moment I'm struggling with the problem that it doesn't find any bluetooth devices in my app but in the bluetooth settings it finds some. (my device runs android 6.x)

My code:

public class MainActivity extends AppCompatActivity {

private ProgressDialog progressDialogBluetoothDiscovery;
private ListView bluetoothDevices;
private ArrayList<String> bluetoothNearbyDevices;
private BluetoothAdapter mBluetoothAdapter;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    ActionBar actionBar = getSupportActionBar();

    bluetoothDevices = (ListView) findViewById(R.id.bluetoothDevicesList);
    mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

    IntentFilter filter = new IntentFilter();
    filter.addAction(BluetoothDevice.ACTION_FOUND);
    filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
    filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
    filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
    registerReceiver(bluetoothBroadcast, filter);

    bluetoothNearbyDevices = new ArrayList<>();

    final FloatingActionButton searchDevices = (FloatingActionButton) findViewById(R.id.search_devices);
    searchDevices.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            searchDevices();
        }
    });
}

@Override
public void onDestroy() {
    super.onDestroy();
    unregisterReceiver(bluetoothBroadcast);
}

private void searchDevices() {
    if (mBluetoothAdapter == null) {
        Toast.makeText(MainActivity.this, getResources().getString(R.string.bluetooth_not_supported), Toast.LENGTH_LONG).show();
        return;
    } else {
        if (!mBluetoothAdapter.isEnabled()) {
            Snackbar.make(findViewById(R.id.coordinatorLayout), getResources().getString(R.string.bluetooth_not_enabled), Snackbar.LENGTH_LONG).setAction(getResources().getString(R.string.activate_bluetooth), new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                    startActivityForResult(enableBtIntent, MainActivity.CONTEXT_INCLUDE_CODE);

                }
            }).show();
        } else {
            scanForDevices();
        }
    }
}

private void scanForDevices() {
    mBluetoothAdapter.startDiscovery();
}

private final BroadcastReceiver bluetoothBroadcast = new BroadcastReceiver() {
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();

        if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)) {
            if (intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, -1) == BluetoothAdapter.STATE_ON) {
                scanForDevices();
            }
        } else if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) {
            progressDialogBluetoothDiscovery = ProgressDialog.show(MainActivity.this, getResources().getString(R.string.bluetooth_discovery_title), getResources().getString(R.string.bluetooth_discovery_message), true);
        } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
            progressDialogBluetoothDiscovery.dismiss();
            ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1, bluetoothNearbyDevices);
            bluetoothDevices.setAdapter(arrayAdapter);
        } else if (BluetoothDevice.ACTION_FOUND.equals(action)) {
            BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            String deviceName = device.getName();
            String deviceHardwareAddress = device.getAddress(); // MAC address
            Toast.makeText(MainActivity.this, deviceName, Toast.LENGTH_LONG).show();
            bluetoothNearbyDevices.add(deviceName);
        }

    }

    };
}

And my manifest:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.package">

<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" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
</manifest>

So do you have any Idea why it doesn't find any device in my app?

Orell Buehler
  • 116
  • 2
  • 9

1 Answers1

0

What version of Android are you running this on? If it is Android 6.x, I believe you need to add the ACCESS_COURSE_LOCATION permission to your manifest.

Below is how run time Permissions work Android 6.0 Marshmallow i.e:

> API level 23

For example:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { 
    switch (ContextCompat.checkSelfPermission(getBaseContext(), Manifest.permission.ACCESS_COARSE_LOCATION)) {
        case PackageManager.PERMISSION_DENIED:
            ((TextView) new AlertDialog.Builder(this)
                    .setTitle("Runtime Permissions up ahead")
                    .setMessage("To find nearby bluetooth devices please click Allow on the runtime permissions popup." )
                    .setNeutralButton("Okay", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            if (ContextCompat.checkSelfPermission(getBaseContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                                ActivityCompat.requestPermissions(DeviceListActivity.this,
                                        new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},
                                        REQUEST_ACCESS_COARSE_LOCATION);
                            }
                        }
                    })
                    .show()
                    .findViewById(android.R.id.message))
                    .setMovementMethod(LinkMovementMethod.getInstance());       
            break;
        case PackageManager.PERMISSION_GRANTED:
            break;
    }
}
Community
  • 1
  • 1
Maveňツ
  • 1
  • 12
  • 50
  • 89
  • Ok I'll try it out. – Orell Buehler Dec 28 '16 at 12:09
  • Somehow I have problems with that ```ActivityCompat.requestPermissions(DeviceListActivity.this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, REQUEST_ACCESS_COARSE_LOCATION);``` the ```REQUEST_ACCESS_COARSE_LOCATION``` and the ```DeviceListActivity.this```gives an error. Even if I replace the ```DeviceListActivity.this``` with ```MainActivity.this```. – Orell Buehler Dec 28 '16 at 12:19
  • @OrellBuehler please specify the erros then only I can help :-) thanks – Maveňツ Dec 29 '16 at 04:42
  • Try this it may be work stackoverflow.com/a/41221852/5488468 – Bipin Bharti Jan 03 '17 at 11:21
  • @OrellBuehler check [this](http://stackoverflow.com/questions/33162152/storage-permission-error-in-marshmallow/41221852#41221852) – Maveňツ Jan 03 '17 at 12:42