I'm trying to scan for BlueTooth devices near me. The phone's built-in BlueTooth scanning sees my iPad, but my code doesn't- it finds no devices. A breakpoint in my BroadcastReceiver doesn't even get triggered.
I'm wondering if I have a scope problem? It doesn't crash, but it doesn't do anything either.
Thanks for any assistance!
Code:
I'm wondering if I have a scope problem? It doesn't crash, but it doesn't do anything either.
Thanks for any assistance!
Code:
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private static final int REQEST_ENABLE_BT = 1;
private String strData;
private BluetoothAdapter mBluetoothAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
strData = "";
//Register for broadcasts when a device is discovered
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mReceiver, filter);
}
@Override
protected void onDestroy() {
super.onDestroy();
//unregister ACTION_FOUND receiver
this.unregisterReceiver(mReceiver);
}
public void FindDevices(View view) {
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null) {
System.exit(0);
}
if (!mBluetoothAdapter.isEnabled()) {
Intent enableBTintent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBTintent, REQEST_ENABLE_BT);
}
//look for other devices
if (mBluetoothAdapter.startDiscovery()) {
Toast.makeText(getApplicationContext(), "Looking...", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "Discovery failed", Toast.LENGTH_SHORT).show();
}
}
// Create a BroadcastReceiver for ACTION_FOUND.
private final BroadcastReceiver mReceiver = 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
TextView textView = findViewById(R.id.editText);
strData = strData + deviceName + " " + deviceHardwareAddress + "\n";
textView.setText(strData);
}
}
};
}