Wednesday, February 22, 2012

Bluetooth Device Periodic Check in Android

public BluetoothAdapter bluetoothAdapter;

//start search
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if(bluetoothAdapter==null)return;
bluetoothAdapter.startDiscovery();
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mReceiver, filter);
bluetoothflag=true;
registerReceiver(mReceiver, new IntentFilter(
BluetoothAdapter.ACTION_DISCOVERY_FINISHED));

///////////////////////////

private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
// When discovery finds a device
if (BluetoothDevice.ACTION_FOUND.equals(action)) {

BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);

String bluetooth = new String("111111111");
BluetoothDevice remote=bluetoothAdapter.getRemoteDevice(bluetooth);

if(device.equals(remote)){
deviceFoundFlag=true;
// bluetoothAdapter.cancelDiscovery();
}

}
else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {

if(!deviceFoundFlag){
//////////alert if no device found
bluetoothflag=false;
}
if(bluetoothflag){
bluetoothAdapter.startDiscovery();
deviceFoundFlag=false;
}

}
}};

No comments:

Post a Comment