ウェブアプリケーション,インジェクション,コマンドインジェクション

Androidアプリ開発 ネットワークプログラミング

Bluetoothの状態をモニタ

Monitoring the State of Bluetooth

もし開発するアプリケーションがBluetoothの接続性を使うなら、
ユーザがBluetoothをオンにしたばかりかどうかを知るのに
役に立ちます。
ここでは、デバイス上のBluetoothの状態をモニタする方法を示します。
例えばもし、バックグラウンドでBluetoothを使うサービスを
書いているのならば、
Bluetoothの状態を細かにモニタして、サービスに合わせて
Bluetoothをスタート、ストップする必要があります。
Bluetoothの状態をモニタするためには、
以下の様にBroadcastReceiver基底クラスの拡張となる
Javaクラスを作ります。

package net.learn2develop.turnonbluetooth;

import android.bluetooth.BluetoothAdapter;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;

public class MyBTBroadcastReceiver extends BroadcaseReceiver{
  @Override
  public void onReceive(Context context, Intent intent){
   int state = intent.getExtras().getInt(BluetoothAdapter.EXTRA_STATE);
   switch(state){
   case BluetoothAdapter.STATE_OFF:
    Toast.makeText(context, "off", Toast.LENGTH_SHORT).show();
    break;
   case BluetoothAdapter.STATE_TURNING_OFF:
    Toast.makeText(context, "Turning off", Toast.LENGTH_SHORT).show();
    break;
   case BluetoothAdapter.STATE_ON:
    Toast.makeText(context, "On", Toast.LENGTH_SHORT).show();
    break;
   case BluetoothAdapter.STATE_TURNING_ON:
    Toast.makeText(context, "Turning On", Toast.LENGTH_SHORT).show();
    break;
   }
  }
}

onReceive()メソッドは、Bluetoothの状態に変化があったときには
いつでも停止します。
ここでは、Bluetoothの4つの状態、”オフになった”、”オフにする処理中”
”オンになった”、”オンにする処理中”をモニタできます。
AndroidManifest.xmlファイルにbroadcastレシーバを
登録しておくことを忘れずに。

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
  package="net.learn2develop.turnonbluetooth"
  android:versionCode="1"
  android:versionName="1.0" >

  <uses-sdk
   android:minSdkVersion="8"
   android:targetSdkVersion="15" />

  <uses-permission android:name="android.permission.BLUETOOTH" />
  <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />

  <application
   android:icon="@drawable/ic_launcher"
   androud:label="@string/app_name"
   android:theme="style/AppTheme" >
   <activity
    android:name=".MainActivity"
   &emps;android:label="@string/title_activity_main" >
    <intent-filter>
     <action android:name="android.intent.action.MAIN" />

     <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
   </activity>

   <receiver android:name=".MyBTBroadcastReceiver" >
    <intent-filter>
     <action android:name=#android.bluetooth.adapter.action.STATE_CHANGED" />
    </intent-filter>
   </receiver>

  </application>
</manifest>

これが完成したら、開発するアプリケーションで
Bluetoothラジオの状態に変化があったときには
いつでも状態をつかめる様になります。

ホーム
便利堂ロゴ
inserted by FC2 system