簡體   English   中英

如何在Android中檢查配對設備的藍牙連接狀態

[英]How to check bluetooth connection state with paired device in Android

我開發了一個藍牙應用程序,它將連接到配對設備並發送消息,但我必須先測試連接。 我嘗試了很多選擇,但沒有任何方法可行。 那么你能給我發一些可以做到的代碼示例嗎? 我創建了一個線程,但是我無法獲得建立“if”函數的良好連接狀態。 這是代碼:

package com.example.szukacz;

import java.lang.reflect.Method;
import java.util.Set;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;


public class MainActivity extends Activity {
    LinearLayout sparowaneUrzadzenia;

    public void lokalizowanie() {
    Intent intencja = new Intent(this, Lokalizator.class);
    startActivity(intencja);

    }

    public void parowanie(View v) {
        Intent intencja = new Intent(this, Parowanie.class);
        startActivity(intencja);

    }

    boolean isRunning;

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            String status = (String)msg.obj;
            if(status == "polaczony") {
                alarm();
                showToast("prawda, zwraca" + status);
            } else {
                showToast("wykonanie x, zwraca: " + status);
            };
        }
    };

    public void alarm() {
        showToast("Alarm!!!");
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        sparowaneUrzadzenia = (LinearLayout) findViewById(R.id.listaUrzadzenGlowna);

        pokazSparowane();



    }

    public void onStop() {
        super.onStop();
        isRunning = false;
    }

    public void onStart() {
        super.onStart();
        Thread testPolaczen = new Thread(new Runnable() {
            public void run() {
                try {
                    for(int i = 0; i < 1000000; i++) {
                        Thread.sleep(5000);
                        testujPolaczenia();
                        int stan = 0;
                        String status = Integer.toString(stan);

                        Message msg = handler.obtainMessage(1, (String)status);

                        if(isRunning == true) {
                            handler.sendMessage(msg);
                        }
                    }
                } catch (Throwable t) {
                    // watek stop
                }
            }
        });
        isRunning = true;
        testPolaczen.start();
    }

    private void testujPolaczenia() {

    }

    public void pokazSparowane(){
        /*
         * Wyświetlanie listy sparowanych urządzeń .
         * */
        Log.d("INFO","Sparowane dla tego urzÄ…dzenia");
        BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();  
        if (pairedDevices.size() > 0) { 
            for (BluetoothDevice device : pairedDevices) {              
                Log.d("INFO",device.getName()+" - "+device.getAddress());

                // dodawanie urzadzen do listy
                Button urzadzenie = new Button(getApplicationContext());
                urzadzenie.setText(device.getName());
            //  urzadzenie.setTextColor(0xffffff); //jak ustawic na czarny kolor napsisów ?

                urzadzenie.setOnClickListener(new OnClickListener() {           

                      @Override
                      public void onClick(View v) 
                      {
                          showToast("klik");
                          lokalizowanie();

                      }    
                    });

                sparowaneUrzadzenia.addView(urzadzenie);
            }
        } else {
            showToast("brak sparowanych urzadzen");
        }
    }



    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
    private void showToast(String message) {
        Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }


}

謝謝!

我遇到了同樣的問題,因為我正在使用可能在運行時使用TTS的應用程序。 我認為除了創建廣播接收器和監視藍牙狀態的變化之外,沒有辦法檢查BluetoothAdapter類是否有任何藍牙設備連接。

在我撓了幾個小時之后,我發現了一種非常微妙的方法來解決這個問題。 我試過,它對我來說效果很好。

AudioManager audioManager = (AudioManager) getApplicationContext.getSystemService(Context.AUDIO_SERVICE);
if (audioManager.isBluetoothA2dpOn()) {
   //audio is currently being routed to bluetooth -> bluetooth is connected
}

資料來源: http//developer.android.com/training/managing-audio/audio-output.html

我認為回答你的問題要遲到,但我認為可以幫助某人:

如果您使用Thread,則必須在create主活動中創建BroadcastReceiver:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_digital_metrix_connexion);
     BroadcastReceiver bState = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if(action.equals(BluetoothAdapter.ACTION_CONNECTION_STATE_CHANGED))
            {
                int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE,
                        BluetoothAdapter.ERROR);
                switch (state)
                {
                    case BluetoothAdapter.ACTION_ACL_CONNECTED:
                    {
                        //Do something you need here
                        System.out.println("Connected");
                        break;
                    }
                    default:
                        System.out.println("Default");
                        break;
                }
            }
        }
    };
}

BluetoothAdapter.STATE_CONNECTED是多個狀態之一,例如,由於BluetoothAdapter.ACTION_ACL_DISCONNECTEDBluetoothAdapter.ACTION_ACL_DISCONNECTED_REQUEST可以檢查設備是否連接或斷開連接。

之后,如果不使用線程,則必須在線程類或主活動中創建過濾器:

IntentFilter filter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);

此過濾器檢查bluetoothadapter狀態。

現在你必須注冊你的過濾器,所以如果你在線程的參數中使用線程傳遞上下文,就像這個context.registerReceiver(bState,filter); 或者在你的主Activity: registerReceiver(bState,filter);

如果您有任何疑問,請不要猶豫,問我。

希望我幫助你。

請閱讀: http//developer.android.com/guide/topics/connectivity/bluetooth.html這是您需要了解的關於藍牙的一切

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM