Device location via bluetooth, android 6.0

Asked

Viewed 100 times

0

I’m having difficulty with bluetooth, exactly with the location of other devices, given that this only happens with android over 6.0, because I tested on a device with android less than 6.0 and worked. I want to know how to make it work, if there’s any permission or anything like that I can include in the code.

Sorry for the lack of technical concept, I’m new in the field of programming, if you can give me a help from now.

DEVICELIST

static private ArrayAdapter<BluetoothDevice> btDevices = null;

private static final UUID SPP_UUID = UUID
        .fromString("8ce255c0-200a-11e0-ac64-0800200c9a66");
// UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");

static private BluetoothSocket mbtSocket = null;
private ArrayAdapter<String> listAdapter;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setTitle("Dispositivos Bluetooth");

    try {
        if (initDevicesList() != 0) {
            this.finish();
            return;
        }

    } catch (Exception ex) {
        this.finish();
        return;
    }

    IntentFilter btIntentFilter = new IntentFilter(
            BluetoothDevice.ACTION_FOUND);
    registerReceiver(mBTReceiver, btIntentFilter);
}

public static BluetoothSocket getSocket() {
    return mbtSocket;
}

private void flushData() {
    try {
        if (mbtSocket != null) {
            mbtSocket.close();
            mbtSocket = null;
        }

        if (mBluetoothAdapter != null) {
            mBluetoothAdapter.cancelDiscovery();
        }

        if (btDevices != null) {
            btDevices.clear();
            btDevices = null;
        }

        if (mArrayAdapter != null) {
            mArrayAdapter.clear();
            mArrayAdapter.notifyDataSetChanged();
            mArrayAdapter.notifyDataSetInvalidated();
            mArrayAdapter = null;
        }

        finalize();
    } catch (Exception ex) {
    } catch (Throwable e) {
    }

}
private int initDevicesList() {
    flushData();

    mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    if (mBluetoothAdapter == null) {
        Toast.makeText(getApplicationContext(),
                "Bluetooth não suportado!!", Toast.LENGTH_LONG).show();
        return -1;
    }

    if (mBluetoothAdapter.isDiscovering()) {
        mBluetoothAdapter.cancelDiscovery();
    }

    mArrayAdapter = new ArrayAdapter<String>(getApplicationContext(), R.layout.activity_devicelist);

    setListAdapter(mArrayAdapter);

    Intent enableBtIntent = new Intent(
            BluetoothAdapter.ACTION_REQUEST_ENABLE);
    try {
        startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
    } catch (Exception ex) {
        return -2;
    }

    Toast.makeText(getApplicationContext(),
            "Obtendo todos os dispositivos Bluetooth disponíveis", Toast.LENGTH_SHORT)
            .show();

    return 0;

}

@Override
protected void onActivityResult(int reqCode, int resultCode, Intent intent) {
    super.onActivityResult(reqCode, resultCode, intent);

    switch (reqCode) {
        case REQUEST_ENABLE_BT:

            if (resultCode == RESULT_OK) {
                Set<BluetoothDevice> btDeviceList = mBluetoothAdapter
                        .getBondedDevices();
                try {
                    if (btDeviceList.size() > 0) {

                        for (BluetoothDevice device : btDeviceList) {
                            if (btDeviceList.contains(device) == false) {

                                btDevices.add(device);

                                mArrayAdapter.add(device.getName() + "\n"
                                        + device.getAddress());
                                mArrayAdapter.notifyDataSetInvalidated();
                            }
                        }
                    }
                } catch (Exception ex) {
                }
            }

            break;
    }
    mBluetoothAdapter.startDiscovery();

}

private final BroadcastReceiver mBTReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (BluetoothDevice.ACTION_FOUND.equals(action)) {
            BluetoothDevice device = intent
                    .getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);

            try {
                if (btDevices == null) {
                    btDevices = new ArrayAdapter<BluetoothDevice>(
                            getApplicationContext(), R.layout.activity_devicelist);
                }

                if (btDevices.getPosition(device) < 0) {
                    btDevices.add(device);
                    mArrayAdapter.add(device.getName() + "\n"
                            + device.getAddress() + "\n" );
                    mArrayAdapter.notifyDataSetInvalidated();
                }
            } catch (Exception ex) {
                ex.fillInStackTrace();
            }
        }
    }
};

@Override
protected void onListItemClick(ListView l, View v, final int position,
                               long id) {
    super.onListItemClick(l, v, position, id);

    if (mBluetoothAdapter == null) {
        return;
    }

    if (mBluetoothAdapter.isDiscovering()) {
        mBluetoothAdapter.cancelDiscovery();
    }

    Toast.makeText(getApplicationContext(),"Conectando à " + btDevices.getItem(position).getName() + ","
            + btDevices.getItem(position).getAddress(), Toast.LENGTH_SHORT).show();

    Thread connectThread = new Thread(new Runnable() {

        @Override
        public void run() {
            try {
                boolean gotuuid = btDevices.getItem(position)
                        .fetchUuidsWithSdp();
                UUID uuid = btDevices.getItem(position).getUuids()[0]
                        .getUuid();
                mbtSocket = btDevices.getItem(position)
                        .createRfcommSocketToServiceRecord(uuid);

                mbtSocket.connect();
            } catch (IOException ex) {
                runOnUiThread(socketErrorRunnable);
                try {
                    mbtSocket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                mbtSocket = null;
                return;
            } finally {
                runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
                        finish();

                    }
                });
            }
        }
    });

    connectThread.start();
}

private Runnable socketErrorRunnable = new Runnable() {

    @Override
    public void run() {
        Toast.makeText(getApplicationContext(),"Não é possível estabelecer conexão", Toast.LENGTH_SHORT).show();
        mBluetoothAdapter.startDiscovery();

    }
};

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    super.onCreateOptionsMenu(menu);

    menu.add(0, Menu.FIRST, Menu.NONE, "Atualizar a digitalização");

    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    super.onOptionsItemSelected(item);

    switch (item.getItemId()) {
        case Menu.FIRST:
            initDevicesList();
            break;
    }

    return true;
}

@Override
protected void onStop()
{
    super.onStop();
    try {
        unregisterReceiver(mBTReceiver);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

MAIN

  • Put at least one snippet of code, if possible.

  • Why do you say it doesn’t work? It makes a mistake?

  • In case it does not give error, however no bluetooth device appears next, the list is empty, but on a device with android below 6.0, appears all devices.

1 answer

0

If you want the application to initiate device discovery or manipulate Bluetooth settings, you also need to declare BLUETOOTH_ADMIN permission in addition to BLUETOOTH permission. Most apps need this permission only to discover local Bluetooth devices. Other features granted by this permission should not be used unless the application is a "power manager" that modifies Bluetooth settings upon user requests.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.