AndroidはBluetoothプログラム1を書く方法を教えます.メッセージを伝え、Bluetoothを起動します.

25614 ワード

注意:私のこのプロジェクトの目的は主に単片機のHC-06 Bluetoothモジュールリファレンス資料:Bluetoothの資料:Android Bluetooth開発(1)Android Bluetooth開発(2)Android Bluetooth開発(3)
1メッセージング
私は説明をこの3つの部分に分けるつもりです.この3つの部分は相対的に独立しています.あなたは一緒に勉強したほうがいいです.私は前に一気に勉強した後、とても理解しにくいと思います.この3つの部分は、Bluetooth機能を起動し、ターゲットのBluetoothデバイスの情報を取得し、Bluetoothデバイスと接続することです.
Bluetoothを話す前に、Android情報伝達に関する2つの重要な知識点を知る必要があります.この2つの知識点は他の場所でも使われています.
1.1放送傍受
Android放送イベント、これは実はよく理解されていて、あなたは放送メッセージを送信することができて、あなたも放送メッセージを受信することができます.ブロードキャストメッセージは、あなた自身から来ているか、システムから来ている可能性があります.主にいくつかのイベントの変化を傍受するために使用され、そのイベントがactionAであると仮定し、actionAが変化した場合、ブロードキャスト傍受を利用して対応する関数に入り、コマンドを実行することができます.この部分の知識は難しくありません.ネット上のチュートリアルがたくさんあるので、自分で書かないでください.放送傍受関数をどのように書くかを学ぶ必要があります.ブロードキャストリスニング関数の登録方法ブロードキャストの送信方法
1.2 Handler、Message、Looper
この3つの面倒なのは、Androidのメッセージメカニズムを消化するのに時間がかかることです(1)Androidのメッセージメカニズム(2)主スレッドにHandlerクラスのインスタンスを作成し、情報受信機能を実現する方法を知っておく必要がありますか?どのように他の場所でMessageクラスでデータを包装し、メインスレッドのhandlerインスタンスでメインスレッドに情報を送信しますか?サブスレッドでLooperとHandlerを使用してサブスレッドの情報受信機を作成する方法
このネット上にもチュートリアルがたくさんありますが、もう少しお話しします.メッセージング者AがBにメッセージを渡すつもりであると仮定すると、Bがプライマリスレッドであるか、Bがサブスレッドであるかの2つに分けられる.なぜこの2つの状況を区別するのか.なぜなら、Handleを使用してメッセージを転送すると、Looperで実装され、各スレッドに1つのLooperしか存在しないループプログラムに入るからです.プライマリ・スレッドのデフォルトにはLooperがあり、サブスレッドのLooperは自分で作成する必要があります.このループプログラムでは,メッセージが伝わってくるか否かを判断し続け,あれば処理し,なければループを継続する.メッセージ処理のメカニズムはMessageQueueによって実現され,その本質はキューであり,先着のメッセージが先に処理され,後着のメッセージが後処理される.
1.2.1メッセージ受信者Bがプライマリスレッドである場合
デフォルトでLooperがあるので、Handlerクラスのメンバーを直接作成すればいいです
private Handler handler = new Handler() {
    @Override
    public void handleMessage(Message msg) {
        super.handleMessage(msg);
        //      Message      。
        switch (msg.what)
        {
            //    +    
        }
    }
};

1.2.2メッセージ受信者Bがプライマリスレッドである場合
なぜ次の文がmHandlerをスレッドのLooperにバインドできるのかについては、静的に実現されていることをネットで調べることができます.
//     
void run(){
	Looper.prepare();                            //    Looper
	mHandler= new Handler() {                    //         
	    public void handleMessage(Message msg) {
	        int what = msg.what;
	        Object obj = msg.obj;
	        switch (what) {
	            //             
	        }
	    }
	};
	Looper.loop();                                //     
}

1.2.3メッセージの送信
// Message     
Message msg = new Message();
msg.what = 1;//         
msg.arg1 = 1;//        
msg.arg2 = 1;//        
msg.obj = "             ,     ,    ";//      
handler.sendMessage(msg);//    
//  ,handler      handler,           handler     

2 Bluetoothの起動
まず最も簡単な部分についてお話しし、Bluetoothを起動します.
2.1 Bluetoothアクセス権
AndroidManifestでxmlファイルに権限を追加manifestプロパティに、アプリケーションプロパティに次の内容を追加します.
<uses-permission android:name="android.permission.BLUETOOTH" />
<!--        -->
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<!--                 -->

2.2 Bluetooth機能の起動
私は今、携帯電話にBluetoothを起動させる機能を実現すればいいです.1)Bluetoothアダプタを取得し、後で使用する
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

2)Bluetooth機能をオンにしてみる
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
context.startActivity(enableBtIntent);
//           ,          Context    
//        ,     startActivity(enableBtIntent);

3)ブロードキャストリスニングブルートゥースオン状態は実は2)でブルートゥースオン機能を実現できますが、ブルートゥースがいつオンになるかを検出して指定プログラムを自動的に実行するには、ブロードキャストリスニングを利用する必要があります.ブロードキャスト傍受の受信クラスを先に確立する
private class BluetoothStateBroadcastReceive extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();//        
            BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            switch (action) {//         
            	//          
                case BluetoothAdapter.ACTION_STATE_CHANGED:
                    int blueState = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, 0);//        
                    if (blueState == BluetoothAdapter.STATE_ON) {
                        try {
                            //      ,          
                           context.unregisterReceiver(bluetoothStateBroadcastReceive);
                        } catch (Exception e) {
                            Log.d("    ", "      ,       ");
                        }
                    }
                    //         
                    
            }
        }
    }

4)ブロードキャスト傍受関数の登録
//         ,             ,             
BluetoothStateBroadcastReceive bluetoothStateBroadcastReceive = new BluetoothStateBroadcastReceive();
//      
IntentFilter filter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);      
//              
context.registerReceiver(bluetoothStateBroadcastReceive,filter);

最後に、Bluetoothを起動する部分の完全なコードを添付します.
public class BlueToothTool {
	//      
	//       
    BluetoothAdapter mBluetoothAdapter;//     
    Context context;
    Handler handlerToMain;

	//    
	private BlueToothTool(){
		super();
	}

	public BlueToothTool(BluetoothAdapter mBluetoothAdapter, Context context, Handler handler){
		this.mBluetoothAdapter = mBluetoothAdapter;
		this.context = context;
		this.handlerToMain = handler;
		//      
		BlueToothFuctionStart();
    }

	/**
     * 1.        
     */
    private void BlueToothFuctionStart(){
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if(mBluetoothAdapter!=null){
            //           ,  startActivity      ,                     
            if(!mBluetoothAdapter.isEnabled()) {
                //        
                Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                context.startActivity(enableBtIntent);
                //              
                //   IntentFilter  
                IntentFilter filter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);      //         Action
                context.registerReceiver(bluetoothStateBroadcastReceive,filter);
            }else{
                //       
                //          
                //2.1        
            }
        }else{
            Toast.makeText(context,"           ",Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 1.1             
     */
     private BluetoothStateBroadcastReceive bluetoothStateBroadcastReceive = new BluetoothStateBroadcastReceive();
    private class BluetoothStateBroadcastReceive extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            switch (action) {
                case BluetoothAdapter.ACTION_STATE_CHANGED:
                    int blueState = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, 0);
                    if (blueState == BluetoothAdapter.STATE_ON) {
                        try {
                            //    
                            context.unregisterReceiver(bluetoothStateBroadcastReceive);
                        } catch (Exception e) {
                            Log.d("    ", "      ,       ");
                        }
                    }
                    //     
                    //          
                    //2.1        
            }
        }
    }
}

これは2番目の内容です.AndroidはBluetoothプログラム2を書く方法を教えてくれます.目標情報を取得します.