fc2ブログ

なんかいろいろこんぴゅーたかんけいのなぐりがき

なんか勉強しているこんぴゅーた関係のことのメモやそれ以外のことを書こうかなあ...

logs

Android Bluetoothプログラミング

AndroidのBluetoothプログラミングは資料が少なくて大変だが、とりあえず簡単なコードをかいてみた。
このプログラムではBluetoothの電源がOFFであればONにし、ONであったなら、既にピアリングしているデバイスの情報をログに出力する。

パッケージ名はプロジェクトで指定したものに変更し、マニフェストファイルで
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
を記述してパーミッションを得ないといけない。
さらにOSは2.0.1だっけか、それくらい以上でなければならないようである。
以下プログラム



package foo.bar.searchBT;

import java.util.Set;
import java.util.Vector;

import android.app.Activity;
import android.content.Intent;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

public class SerachBluetoothDevices extends Activity {
private static final int REQUEST_ENABLE_BT = 1;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void onStart()
{
super.onStart();
BluetoothAdapter bluetooth_adapter = BluetoothAdapter.getDefaultAdapter();
//端末がBluetoothに対応していない場合終了する
if(bluetooth_adapter == null)
{
Toast.makeText(this, "この端末はBluetoothを利用できません。終了します。", Toast.LENGTH_LONG);
finish();
}
//もしBluetoothがOFFになっていたらONにするようにする
if(!bluetooth_adapter.isEnabled())
{
Intent enable_bt = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enable_bt,REQUEST_ENABLE_BT);
}
//もしBluetoothがONに最初からなっていたら
else
{
Vector<BluetoothDevice> devices = new Vector<BluetoothDevice>();
//getBoundedDevicesによってピアリングが既になされているデバイスを取得する
Set<BluetoothDevice> paired_devices = bluetooth_adapter.getBondedDevices();
//BluetoothDeviceのインスタンスをdevicesインスタンスに追加していく
for(BluetoothDevice device : paired_devices)
{
devices.add(device);
}
//devicesに保存されたBluetoothDeviceインスタンスを利用して順番に情報をログに出力していく
for(int i=0;i<devices.size();i++) Log.d("debug",devices.elementAt(i).getName()+":"+devices.elementAt(i).getAddress());

}

}
}

スポンサーサイト



トラックバックURL

http://ilovevim.blog42.fc2.com/tb.php/139-89fcd75e

この記事へのトラックバック

この記事へのコメント

コメント投稿フォーム

Paging Navigation

Navigations, etc.