Получить силу сигнала Bluetooth

Я хочу получить уровень сигнала Bluetooth другого устройства, подключенного к моему телефону,

Как я могу получить силу сигнала Bluetooth?

Я пытался много искать в Google и не нашел ответа.

Кто-нибудь знает, как я могу это реализовать?

это моя активность:

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        registerReceiver(receiver, new IntentFilter(BluetoothDevice.ACTION_FOUND));


    }

    @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 final BroadcastReceiver receiver = new BroadcastReceiver(){
        @Override
        public void onReceive(Context context, Intent intent) {

            String action = intent.getAction();
            if(BluetoothDevice.ACTION_FOUND.equals(action)) {
                int rssi = intent.getShortExtra(BluetoothDevice.EXTRA_RSSI,Short.MIN_VALUE);
                Toast.makeText(getApplicationContext(),"  RSSI: " + rssi + "dBm", Toast.LENGTH_SHORT).show();
            }
        }
    };

}

У меня также есть разрешение Bluetooth в моем файле манифеста.

4 ответа

Решение

Чтобы получить сигнал, вы можете проверить BluetoothI RSSI, вы можете прочитать RSSI для подключенных устройств или выполнить обнаружение Bluetooth, чтобы проверить RSSI для любых соседних устройств.

По сути, обнаружение bluetooth - это широковещательная рассылка на все станции в пределах диапазона для ответа. Когда каждое устройство отвечает, Android запускает намерение ACTION_FOUND. В рамках этого намерения вы можете получить дополнительную EXTRA_RSSI для получения RSSI.

Обратите внимание, что не все устройства Bluetooth поддерживают RSSI.

Также по теме: Android IRC Office Hours Вопрос о Android Bluetooth RSSIвот пример

private final BroadcastReceiver receiver = new BroadcastReceiver(){
    @Override
    public void onReceive(Context context, Intent intent) {

        String action = intent.getAction();
        if(BluetoothDevice.ACTION_FOUND.equals(action)) {
            int  rssi = intent.getShortExtra(BluetoothDevice.EXTRA_RSSI,Short.MIN_VALUE);
            Toast.makeText(getApplicationContext(),"  RSSI: " + rssi + "dBm", Toast.LENGTH_SHORT).show();
        }
    }
};

Я думаю, что ваш код в порядке, но вам нужно реализовать startDiscovery() для того, чтобы увидеть результаты.

Истина в том, что BluetoothDevice.EXTRA_RSSI работает только для обнаружения устройств, когда вы подключаетесь к одному из них, вы больше не можете получить его RSSI.

Здесь я разработал очень простой пример Activity, который позволяет вам видеть RSSI устройств рядом с вами. Сначала вам нужно добавить TextView и кнопку в макет, затем включить адаптер Bluetooth, а затем просто нажать кнопку.

package com.in2apps.rssi;

import android.os.Bundle;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class RSSIActivity extends Activity {

    private BluetoothAdapter BTAdapter = BluetoothAdapter.getDefaultAdapter();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_rssi);
        registerReceiver(receiver, new IntentFilter(BluetoothDevice.ACTION_FOUND));

        Button boton = (Button) findViewById(R.id.button1);
        boton.setOnClickListener(new OnClickListener(){
            public void onClick(View v) {
                BTAdapter.startDiscovery();
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_rssi, menu);
        return true;
    }

    private final BroadcastReceiver receiver = new BroadcastReceiver(){
        @Override
        public void onReceive(Context context, Intent intent) {

            String action = intent.getAction();
            if(BluetoothDevice.ACTION_FOUND.equals(action)) {
                int rssi = intent.getShortExtra(BluetoothDevice.EXTRA_RSSI,Short.MIN_VALUE);
                String name = intent.getStringExtra(BluetoothDevice.EXTRA_NAME);
                TextView rssi_msg = (TextView) findViewById(R.id.textView1);
                rssi_msg.setText(rssi_msg.getText() + name + " => " + rssi + "dBm\n");
            }
        }
    };
}

Это выглядит так:

RSSI Detection - пример для Android

Необходимый API был представлен в API 18 (Android 4.3). Вам нужно позвонить BluetoothGatt#readRemoteRssi() инициировать запрос. Ответ отображается на BluetoothCallback#onReadRemoteRssi() Перезвоните. (Это объект обратного вызова, который обрабатывает соединение, обнаружение, чтение характеристик и т. Д.)

Материал вещательного приемника больше не требуется.

Вы можете получить сигнал силы BluetoothDevice, используя его rssi. Это можно сделать с помощью BluetoothAdapter, чтобы получить ограниченные устройства.

Если у вас есть тот, который вас интересует, просто вызовите connectGatt() и определите новый BluetoothGattCallback. Это интерфейс, который предоставляет несколько методов для переопределения. Два написанных ниже позволят вам иметь rssi каждый раз, когда состояние соединения изменяется.

@Override
protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);

  // Get the default bluetoothAdapter to store bonded devices into a Set of BluetoothDevice(s)
  BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
  // It will work if your bluetooth device is already bounded to your phone
  // If not, you can use the startDiscovery() method and connect to your device
  Set<BluetoothDevice> bluetoothDeviceSet = bluetoothAdapter.getBondedDevices();

  for (BluetoothDevice bluetoothDevice : bluetoothDeviceSet) {
    bluetoothDevice.connectGatt(this, true, new BluetoothGattCallback() {
      @Override
      public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
        super.onConnectionStateChange(gatt, status, newState);
      }
      @Override
      public void onReadRemoteRssi(BluetoothGatt gatt, int rssi, int status) {
        if(status == BluetoothGatt.GATT_SUCCESS)
          Log.d("BluetoothRssi", String.format("BluetoothGat ReadRssi[%d]", rssi));
      }
    });
  }

}

ПРИМЕЧАНИЕ. Для этого образца требуется следующее разрешение, указанное в файле манифеста.

<uses-permission android:name="android.permission.BLUETOOTH" />
Другие вопросы по тегам