I'm currently learning basics of Bluetooth technology. The code is from some tutorial I have found and it doesn't work. I've tried code from many tutorials and I can't find any Bluetooth devices. I'm wondering is something wrong with the code or is it my phone's fault (I haven't tried it on different device yet). I'm writing in Java. I'm not sure but I think something is wrong with function onReceive because it doesn't show a Log message.
Here's my code:
public class MainActivity extends AppCompatActivity {
ListView lv;
BroadcastReceiver mBroadcastReceiver;
BluetoothAdapter mBluetoothAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv = findViewById(R.id.listview);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null) {
Toast.makeText(this, "BT not supported", Toast.LENGTH_SHORT).show();
} else {
if (!mBluetoothAdapter.isEnabled()) {
Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "asdasd", Toast.LENGTH_SHORT).show();
}
startActivityForResult(intent, 1);
}
}
}
@Override
protected void onResume(){
super.onResume();
if(ContextCompat.checkSelfPermission(MainActivity.this,Manifest.permission.ACCESS_FINE_LOCATION)!=PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.ACCESS_FINE_LOCATION},2);
}
if(ContextCompat.checkSelfPermission(MainActivity.this,Manifest.permission.ACCESS_COARSE_LOCATION)!=PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},4);
}
if(ContextCompat.checkSelfPermission(MainActivity.this,Manifest.permission.BLUETOOTH_ADMIN)!=PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.BLUETOOTH_ADMIN},3);
}
ArrayList<String> arrayList =new ArrayList<>();
mBluetoothAdapter.startDiscovery();
mBroadcastReceiver=new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action=intent.getAction();
if(action.equals(BluetoothDevice.ACTION_FOUND)){
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
Log.i("Bluetooth DEVICES ",device.getName());
}
if(arrayList.size()!=0) {
ArrayAdapter<String> itemAdapter = new ArrayAdapter<>(getApplicationContext(), android.R.layout.simple_list_item_1, arrayList);
lv.setAdapter(itemAdapter);
}
}
};
IntentFilter intentFilter =new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mBroadcastReceiver,intentFilter);
}
@Override
protected void onDestroy(){
super.onDestroy();
unregisterReceiver(mBroadcastReceiver);
}
}