SHOEISHA iD

※旧SEメンバーシップ会員の方は、同じ登録情報(メールアドレス&パスワード)でログインいただけます

CodeZine編集部では、現場で活躍するデベロッパーをスターにするためのカンファレンス「Developers Summit」や、エンジニアの生きざまをブーストするためのイベント「Developers Boost」など、さまざまなカンファレンスを企画・運営しています。

特集記事(AD)

ソフトとハードのつくり手が自由につながるIoTプラットフォーム「Linking」の概要と使い方

  • このエントリーをはてなブックマークに追加

Linkingアプリ接続/切断検知方法

 次に、Linkingアプリと周辺デバイスの接続/切断を検知する方法について説明します。

 NotifyConnectクラスにobserver(NotifyConnect.ConnectInterface)を設定することで接続/切断通知を受けることが可能になります。

 そして、通知を受けた時の情報は、以下の名称でローカルデータとしてSharedPreferencesに格納されます。

  • 接続情報:DeviceConnectInformation
  • 切断情報:DeviceDisconnectInformation

 今回はLinkingServiceを実装することで、バックグラウンドでも周辺デバイスに対する接続/切断を検知しNotificationを表示できるようにします。

LinkingService.java
import com.nttdocomo.android.sdaiflib.Define;
import com.nttdocomo.android.sdaiflib.NotifyConnect;

public class LinkingService extends Service {
    private NotifyConnect mNotifyConnect;
    private MyConnectInterface mMyConnectInterface;

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        mMyConnectInterface = new MyConnectInterface();
        mNotifyConnect = new NotifyConnect(this, mMyConnectInterface);
    }

   @Override
   protected void onDestroy() {
       super.onDestroy();
       mNotifyConnect.release();
   }

    private void sendNotification(String title, String text){
        NotificationCompat.Builder notificationBuilder =
                new NotificationCompat.Builder(this)
                        .setSmallIcon(android.R.drawable.sym_def_app_icon)
                        .setContentTitle(title)
                        .setContentText(text);


        NotificationManagerCompat notificationManager =
                NotificationManagerCompat.from(this);
        notificationManager.notify(0, notificationBuilder.build());
    }

    // 接続と切断の通知を受信する
    class MyConnectInterface implements NotifyConnect.ConnectInterface {
        @Override
        public void onConnect() {
            // 接続通知
            SharedPreferences preference = getSharedPreferences(Define.ConnectInfo, Context.MODE_PRIVATE);
            String deviceName = preference.getString("DEVICE_NAME", "");
            sendNotification("接続通知", "デバイス[" + deviceName +"]が接続されました");
        }

        @Override
        public void onDisconnect() {
            // 切断通知
            SharedPreferences preference = getSharedPreferences(Define.DisconnectInfo, Context.MODE_PRIVATE);
            String deviceName = preference.getString("DEVICE_NAME", "");
            sendNotification("切断通知", "デバイス[" + deviceName +"]切断されました");
        }
    }
}

ビーコンからデータを受信

 次に、ビーコンからデータを受信する方法について説明します。

 BeaconScannerクラスを利用することで、ビーコンのスキャン開始/停止依頼を行うことができます。スキャンは定期的に実行され、ビーコンが検出された場合にはビーコンの情報を取得することができます。

 マニフェストファイルには、ビーコン機器通知対応の宣言を記載してください。また受信するレシーバークラスには、IntentFilterの設定が必要です。

AndroidManifest.xml
<application>
   ~中略~
   <meta-data
     android:name="com.nttdocomo.android.smartdeviceagent.feature.beacon" android:value="true" />
   ~中略~

    <receiver
        android:name=".MainActivity$MyBeaconReceiverBase"
        android:exported="true" >
        <intent-filter>
            <action android:name="com.nttdocomo.android.smartdeviceagent.action.BEACON_SCAN_RESULT" />
            <action android:name="com.nttdocomo.android.smartdeviceagent.action.BEACON_SCAN_STATE" />
        </intent-filter>
    </receiver>
</application>
MainActivity.java
import com.nttdocomo.android.sdaiflib.BeaconData;
import com.nttdocomo.android.sdaiflib.BeaconReceiverBase;
import com.nttdocomo.android.sdaiflib.BeaconScanner;

public class MainActivity extends Activity {

    private BeaconScanner mBeaconScanner;
    private MyBeaconReceiverBase mMyBeaconReceiverBase;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        ~中略~
        mBeaconScanner = new BeaconScanner(this);
        mMyBeaconReceiverBase = new MyBeaconReceiverBase();
    }

    public void onStartBeaconScan(View view) {
        // サービスIDを指定
        // すべての検出されたビーコンサービスID/データが含まれるビーコン情報を通知
        mBeaconScanner.startScan(new int[] {0} );
    }

    public void onStopBeaconScan(View view) {
        // スキャン停止依頼
        mBeaconScanner.stopScan();
    }

    // ビーコンスキャンの結果を受信するレシーバー
    public static class MyBeaconReceiverBase extends BeaconReceiverBase {

        public MyBeaconReceiverBase() {
        }

        @Override
        protected void onReceiveScanResult(BeaconData beaconData) {
            Log.d(TAG, "ビーコン検出時間" + beaconData.getTimestamp());
            Log.d(TAG, "距離の種別:" + beaconData.getDistance());
            Log.d(TAG, "バッテリー:" + beaconData.getBatteryPower() + "%");
        }

        @Override
        protected void onReceiveScanState(int scanState, int detail) {
            if (scanState == 0 && detail == 0) {
                Log.d(TAG, "スキャン実行中");
            } else {
                Log.d(TAG, "スキャン要求に失敗しました : " + detail);
            }
        }
    }
}

次のページ
周辺デバイス情報の取得

この記事は参考になりましたか?

  • このエントリーをはてなブックマークに追加
特集記事連載記事一覧

もっと読む

この記事の著者

株式会社ブリリアントサービス 角野 宏樹(カクノ ヒロキ)

 1990年生まれ。神戸電子専門学校のゲーム学科を卒業後、Androidの仕事がしたいと思い株式会社ブリリアントサービスに就職。中学、高校時代にバレーボールで培った体力を元にAndroidアプリを中心としたスマートフォン開発事業に携わっている。バレーボールとロードバイクとアニメが趣味。

※プロフィールは、執筆時点、または直近の記事の寄稿時点での内容です

【AD】本記事の内容は記事掲載開始時点のものです 企画・制作 株式会社翔泳社

この記事は参考になりましたか?

この記事をシェア

  • このエントリーをはてなブックマークに追加
CodeZine(コードジン)
https://codezine.jp/article/detail/9224 2016/02/17 14:00

おすすめ

アクセスランキング

アクセスランキング

イベント

CodeZine編集部では、現場で活躍するデベロッパーをスターにするためのカンファレンス「Developers Summit」や、エンジニアの生きざまをブーストするためのイベント「Developers Boost」など、さまざまなカンファレンスを企画・運営しています。

新規会員登録無料のご案内

  • ・全ての過去記事が閲覧できます
  • ・会員限定メルマガを受信できます

メールバックナンバー

アクセスランキング

アクセスランキング