Here is the test code I'm using:
public class IOConnectDirect extends Activity {
private static final String TAG = "IOConnectDirect";
private static final int REQCODE_BLUETOOTH_RESULT = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.i(TAG, "onCreate");
setTitle(getTitle() + "--" + TAG);
Intent intentBluetooth = new Intent();
intentBluetooth.setAction("android.bluetooth.devicepicker.action.LAUNCH");
startActivityForResult(intentBluetooth, REQCODE_BLUETOOTH_RESULT);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.i(TAG, "onActivityResult(" + requestCode +"," + resultCode + ")");
switch (requestCode) {
case REQCODE_BLUETOOTH_RESULT:
Log.i(TAG, "requestCode = REQCODE_BLUETOOTH_RESULT");
if(resultCode == RESULT_OK) {
Log.i(TAG, "RESULT_OK");
Bundle extras = data.getExtras();
if(extras != null) {
Log.i(TAG, "Bundle ok");
}
}
else {
Log.i(TAG, "!RESULT_OK = FAILED(" + resultCode + ")");
Toast.makeText(this, "Failed(" + resultCode +")", Toast.LENGTH_SHORT).show();
}
break;
default:
Log.i(TAG, "requestCode = ????");
break;
}
}
}
Here is the output of Logcat:
I/IOConnectDirect(14956): onActivityResult(0,0)
I/IOConnectDirect(14956): requestCode = REQCODE_BLUETOOTH_RESULT
I/IOConnectDirect(14956): !RESULT_OK = FAILED(0)
The code works (you need to activate Bluetooth first), I just can not get it to do what I want in order to get the name and address of the Bluetooth device that I selected from this activity.
Note:
- I am not trying to connect. I just need device information.
- I am familiar with other methods to do this, as in the example of Bluetooth Bluetooth Chat
UPDATE
I end up using BroadcastReceiver
public class IOConnectDirect extends Activity {
private static final String TAG = "IOConnectDirect";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.i(TAG, "onCreate");
BluetoothConnectActivityReceiver mBluetoothPickerReceiver = new BluetoothConnectActivityReceiver();
registerReceiver(mBluetoothPickerReceiver, new IntentFilter(BluetoothDevicePicker.ACTION_DEVICE_SELECTED));
startActivity(new Intent(BluetoothDevicePicker.ACTION_LAUNCH)
.putExtra(BluetoothDevicePicker.EXTRA_NEED_AUTH, false)
.putExtra(BluetoothDevicePicker.EXTRA_FILTER_TYPE, BluetoothDevicePicker.FILTER_TYPE_ALL)
.setFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS));
}
public class BluetoothConnectActivityReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if(BluetoothDevicePicker.ACTION_DEVICE_SELECTED.equals(intent.getAction())) {
context.unregisterReceiver(this);
BluetoothDevice device = (BluetoothDevice) intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
Toast.makeText(context, "device" + device.getAddress(), Toast.LENGTH_SHORT).show();
}
}
}
source
share