Monday, May 23, 2011

Detect Bluetooth state

Introduced from API Level 5, BluetoothAdapter lets you perform fundamental Bluetooth tasks, such as initiate device discovery, query a list of bonded (paired) devices, instantiate a BluetoothDevice using a known MAC address, and create a BluetoothServerSocket to listen for connection requests from other devices.

It's a exercise to detect Bluetooth state.

Detect Bluetooth state

Modify AndroidManifest.xml to grant permission of "android.permission.BLUETOOTH".
<?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>


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"
/>
</LinearLayout>


AndroidBluetooth.java
package com.exercise.AndroidBluetooth;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.os.Bundle;
import android.widget.TextView;

public class AndroidBluetooth extends Activity {
/** Called when the activity is first created. */

TextView stateBluetooth;
BluetoothAdapter bluetoothAdapter;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

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

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.");
}
}else{
stateBluetooth.setText("Bluetooth is NOT Enabled!");
}
}



}
}


Download the files.

next:
- Turn-On BlueTooth using intent of BluetoothAdapter.ACTION_REQUEST_ENABLE

1 comment:

  1. suppose I have saved mac address of a device in one file using android application.
    Later I want to check whether that mac addressed devices is still sending connection request. Is it possible?. Hope somebody will help.

    ReplyDelete