Here is my code
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
private final BroadcastReceiver mReceiver = 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);
devices.add(device.getName());
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
mBtAdapter.startDiscovery();
Toast.makeText(MainActivity.this,"Discovering "+devices.size(),Toast.LENGTH_SHORT).show();
ArrayAdapter arrayAdapter=new ArrayAdapter(MainActivity.this,android.R.layout.simple_list_item_1,devices);
listView.setAdapter(arrayAdapter);
}
}
};
ListView listView;
ArrayList<String> devices;
private BluetoothAdapter mBtAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView=(ListView) findViewById(R.id.listView);
devices=new ArrayList<String>();
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
this.registerReceiver(mReceiver, filter);
filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
this.registerReceiver(mReceiver, filter);
mBtAdapter = BluetoothAdapter.getDefaultAdapter();
if(!mBtAdapter.isEnabled()){
mBtAdapter.enable();
}
mBtAdapter.startDiscovery();
}
@Override
protected void onDestroy(){
super.onDestroy();
mBtAdapter.cancelDiscovery();
unregisterReceiver(mReceiver);
}
}
Problem is it always displays Discovering 0 as the size of devices arrayList is always 0. But phone detects the nearby available devices as in picture below Screenshot of phone bluetooth settings .I think my app broadcast receiver doesn't detect bluetooth devices available because there is an error in my code.Please help me