Thursday, May 26, 2011

Start Bluetooth Discoverable and register BroadcastReceiver for ACTION_SCAN_MODE_CHANGED

To enable Bluetooth Discoverable, we can start activity with intent of BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE. we can also provide expected discoverable duration via Extra.

To monitor the scan mode change in Bluetooth device, we can register our BroadcastReceiver for BluetoothAdapter.ACTION_SCAN_MODE_CHANGED. The BroadcastReceiver have t be unregister in onDestroy().

Here is a exercise to Start Bluetooth Discoverable.

Start Bluetooth Discoverable and register BroadcastReceiver for ACTION_SCAN_MODE_CHANGED

AndroidBluetooth.java
package com.exercise.AndroidBluetooth;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class AndroidBluetooth extends Activity {

private static final int REQUEST_ENABLE_BT = 1;
private static final int REQUEST_Turn_On_Discoverable = 3;

Spinner spnDiscoverableDuration;
Button btnTurnOnDiscoverable;
TextView stateBluetooth;
BluetoothAdapter bluetoothAdapter;

String[] optDiscoverableDur = {"10 sec", "60 sec", "120 sec", "240 sec", "300 sec"};
int[] valueDiscoverableDur = {10, 60, 120, 240, 300};

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

spnDiscoverableDuration = (Spinner)findViewById(R.id.discoverableduration);
btnTurnOnDiscoverable = (Button)findViewById(R.id.turnondiscoverable);

stateBluetooth = (TextView)findViewById(R.id.bluetoothstate);
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

CheckBlueToothState();

btnTurnOnDiscoverable.setOnClickListener(btnTurnOnDiscoverableOnClickListener);

ArrayAdapter<String> adapterDiscoverableDur = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, optDiscoverableDur);
adapterDiscoverableDur.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spnDiscoverableDuration.setAdapter(adapterDiscoverableDur);

registerReceiver(ScanModeChangedReceiver,
new IntentFilter(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED));
}

@Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
unregisterReceiver(ScanModeChangedReceiver);
}

private void CheckBlueToothState(){
if (bluetoothAdapter == null){
stateBluetooth.setText("Bluetooth NOT support");
}else{
if (bluetoothAdapter.isEnabled()){
if(bluetoothAdapter.isDiscovering()){
stateBluetooth.setText("Bluetooth is currently in device discovery process.");
}else{
stateBluetooth.setText("Bluetooth is Enabled.");
btnTurnOnDiscoverable.setEnabled(true);
}
}else{
stateBluetooth.setText("Bluetooth is NOT Enabled!");
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
}
}

private Button.OnClickListener btnTurnOnDiscoverableOnClickListener
= new Button.OnClickListener(){

@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent discoverableIntent
= new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
int dur = valueDiscoverableDur[(int)spnDiscoverableDuration.getSelectedItemId()];
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, dur);
startActivityForResult(discoverableIntent, REQUEST_Turn_On_Discoverable);
}};

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
if(requestCode == REQUEST_ENABLE_BT){
CheckBlueToothState();
}if (requestCode == REQUEST_Turn_On_Discoverable){
if(resultCode == RESULT_OK){

}else if (resultCode == RESULT_CANCELED){
Toast.makeText(AndroidBluetooth.this,
"User Canceled",
Toast.LENGTH_LONG).show();
}
}
}

private final BroadcastReceiver ScanModeChangedReceiver = new BroadcastReceiver(){

@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
String action = intent.getAction();
if(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED.equals(action)) {

int mode = intent.getIntExtra(BluetoothAdapter.EXTRA_SCAN_MODE,
BluetoothAdapter.ERROR);
String strMode = "";

switch(mode){
case BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE:
strMode = "mode changed: SCAN_MODE_CONNECTABLE_DISCOVERABLE";
break;
case BluetoothAdapter.SCAN_MODE_CONNECTABLE:
strMode = "mode changed: SCAN_MODE_CONNECTABLE";
break;
case BluetoothAdapter.SCAN_MODE_NONE:
strMode = "mode changed: SCAN_MODE_NONE";
break;
}

Toast.makeText(AndroidBluetooth.this,
strMode, Toast.LENGTH_LONG).show();
}
}};

}


main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
<TextView
android:id="@+id/bluetoothstate"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<TextView
android:id="@+id/bluetoothstate"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Set Discoverable Duration"
/>
<Spinner
android:id="@+id/discoverableduration"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<Button
android:id="@+id/turnondiscoverable"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Turn on Discoverable"
android:enabled="false"
/>
</LinearLayout>


Grant permission of "android.permission.BLUETOOTH" in AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.exercise.AndroidBluetooth"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="7" />
<uses-permission android:name="android.permission.BLUETOOTH"></uses-permission>

<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".AndroidBluetooth"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>


Download the files.

Related:
- Get the list of paired Bluetooth devices
- Scan Bluetooth Devices

2 comments:

edwin said...

Hello, I was wondering, could you post a code on how to combine all the bluetooth codes together? From turning on, detect, list paired devices, starting bluetooth and scanning devices? I tried compiling them together but i keep getting errors. Your help is greatly appreciated, Thank you

Anonymous said...

Hii,
I have a requirement where i want to change the Scan Mode on Click of Button.Can we do that.Please provide a solution.