获取RSSI 无非就两种方法,一是在扫描回调时读取,二是在BLE连接之后读取,两种方法都比较简单,关键在于对蓝牙BLE的认识。
那我首先就介绍下在 扫描回调时怎么去读。
因为通常情况下,我们扫描时的设备及信息都是放在界面上,我就拿这个来说吧,
以呈现在列表上为例,首先 适配器的创建
在创建适配器的时候,要加入 addDevice()方法
public ArrayList<BluetoothDevice> mLeDevices;
private LayoutInflater mInflator;
private ArrayList<Integer> mRSSIs;
private ArrayList<byte[]> mRecords;
public MyAdapter() {
super();
mLeDevices = new ArrayList<BluetoothDevice>();
mRSSIs = new ArrayList<Integer>();
mRecords = new ArrayList<byte[]>();
mInflator = MainActivity.this.getLayoutInflater();
}
public void addDevice(BluetoothDevice device,int rssi,byte[] scanRecord) {
if (!mLeDevices.contains(device)) {
if (mScanning) {
mLeDevices.add(device);
mRSSIs.add(rssi);
mRecords.add(scanRecord);
}
}
}
在getView里面添加如下(我的测试的,根据每个人的XML文件不同而适当修改)
ViewHolder holder;
if (convertView == null) {
Log.i("null", " " + position);
holder = new ViewHolder();
convertView = mInflator.inflate(R.layout.item, null);
holder.deviceName = (TextView) convertView
.findViewById(R.id.deviceName);
holder.deviceAddress = (TextView) convertView
.findViewById(R.id.deviceMac);
holder.deviceRssi = (TextView)convertView.findViewById(R.id.deviceRssi);
convertView.setTag(holder);
} else {
Log.i("not-null", " " + position);
holder = (ViewHolder) convertView.getTag();
}
BluetoothDevice device = mLeDevices.get(position);
int rssi = mRSSIs.get(position);
String rssiString = (rssi == 0) ? "N/A" :"RSSI:"+ rssi + " db";
final String deviceName = "设备名称:"+device.getName();
if (deviceName != null && deviceName.length() > 0)
holder.deviceName.setText(deviceName);
holder.deviceAddress.setText("MAC:"+device.getAddress());
holder.deviceRssi.setText(rssiString);
return convertView;
}
private class ViewHolder {
TextView deviceName;
TextView deviceAddress;
TextView deviceRssi;
}
最后 在回调方法中添加如下
myAdapter.addDevice(device,rssi,scanRecord);
myAdapter.notifyDataSetChanged();
关键代码给出,大家自行添加修改
第二种方法就是连接后读取rssi
废话不多说,代码奉上
import com.example.readblerssi.R;
import com.readrssi.ble.BluetoothOperate;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
/**
* MainActivity
* @author Administrator
* FanMo
*
*/
public class MainActivity extends Activity implements OnClickListener {
private static final String TAG = "MainActivity.class";
private Context context = MainActivity.this;
private String scanBluetoothName="Autophix";
private Button btnConnect;
private TextView tvRssi,tvBluetoothName,tvbluetoothMac,tvConnectState;
private BluetoothAdapter mBluetoothAdapter;
private BluetoothOperate mBluetoothOperate;
private static final int REQUEST_ENABLE_BT = 1;
private static final int READRSSI=0;
private static final int CONNECTED=1;
private static final int DISCONNECT=2;
private String bluetoothName, bluetoothMacAddress;
private boolean mScanning = false;
private Handler mHandler;
private static final long SCAN_PERIOD =10000;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON,
WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
setContentView(R.layout.activity_main);
btnConnect=(Button) findViewById(R.id.mainactivity_bluetooth_connect);
btnConnect.setOnClickListener(this);
tvRssi=(TextView) findViewById(R.id.rssi_value);
tvBluetoothName=(TextView) findViewById(R.id.bluetooth_name);
tvbluetoothMac=(TextView) findViewById(R.id.bluetooth_mac);
tvConnectState=(TextView) findViewById(R.id.bluetooth_connect_state);
mHandler = new Handler();
if (!getPackageManager().hasSystemFeature(
PackageManager.FEATURE_BLUETOOTH_LE)) {
showToast("NOT SUPPORT BLE4.0");
} else {
final BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
mBluetoothAdapter = bluetoothManager.getAdapter();
}
if (mBluetoothAdapter == null) {
showToast("NOT SUPPORT BLE4.0");
}
mBluetoothOperate=BluetoothOperate.getInstance(this,mHandlerRssi);
}
@Override
protected void onResume() {
super.onResume();
if (!mBluetoothAdapter.isEnabled()) {
if (!mBluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(
BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case REQUEST_ENABLE_BT:
if (resultCode == RESULT_OK) {
} else {
}
break;
default:
break;
}
}
/**
*
* @param text
* Toast show 方法
*/
private void showToast(String text) {
Toast.makeText(context, text, 1000).show();
}
/**
* 搜索蓝牙设备
*/
@SuppressWarnings("deprecation")
@SuppressLint("NewApi")
private void scanLeDevice(final boolean enable) {
if (enable) {
mHandler.postDelayed(new Runnable() {
@SuppressWarnings("deprecation")
@SuppressLint("NewApi")
@Override
public void run() {
mScanning = false;
mBluetoothAdapter.stopLeScan(mLeScanCallback);
}
}, SCAN_PERIOD);
mScanning = true;
mBluetoothAdapter.startLeScan(mLeScanCallback);
} else {
mScanning = false;
mBluetoothAdapter.stopLeScan(mLeScanCallback);
}
}
@SuppressLint("NewApi")
private BluetoothAdapter.LeScanCallback mLeScanCallback = new BluetoothAdapter.LeScanCallback() {
@Override
public void onLeScan(final BluetoothDevice device, int rssi,
byte[] scanRecord) {
runOnUiThread(new Runnable() {
@SuppressWarnings("deprecation")
@SuppressLint({ "NewApi", "HandlerLeak" })
@Override
public void run() {
bluetoothName = device.getName();
bluetoothMacAddress = device.getAddress();
mBluetoothAdapter.stopLeScan(mLeScanCallback);
mBluetoothOperate.setmDeviceAddress(bluetoothMacAddress);
tvBluetoothName.setText(device.getName()+"");
tvbluetoothMac.setText(bluetoothMacAddress+"");
Log.d(TAG, "扫描到蓝牙设备 蓝牙名字="+bluetoothName+"MAC地址="+bluetoothMacAddress);
mBluetoothOperate.OpenBluetoothService();
scanLeDevice(true);
}
});
}
};
@SuppressLint("HandlerLeak")
Handler mHandlerRssi=new Handler(){
@SuppressLint("HandlerLeak")
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what) {
case READRSSI:
String rss=msg.obj.toString();
tvRssi.setText(rss+"");
break;
case CONNECTED:
tvConnectState.setText("已链接上");
btnConnect.setText("CONNECTED");
break;
case DISCONNECT:
tvConnectState.setText("链接断开");
btnConnect.setText("Scanning");
tvRssi.setText("null");
break;
default:
break;
}
}
};
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.mainactivity_bluetooth_connect:
if (!mScanning) {
scanLeDevice(true);
btnConnect.setText("Scanning");
} else {
scanLeDevice(false);
btnConnect.setText("connect");
}
break;
default:
break;
}
}
@Override
protected void onDestroy() {
super.onDestroy();
mBluetoothOperate.CloseBluetoothService();
}
}
关键代码 在BluetoothService.java中添加
public boolean getRssiVal() {
if (mBluetoothGatt == null)
return false;
return mBluetoothGatt.readRemoteRssi();
}
/**
* 读取蓝牙RSSi线程
*/
Thread readRSSI =new Thread(){
int Rssi=0;
@Override
public void run() {
// TODO Auto-generated method stub
super.run();
while (isReadRssi){
try {
sleep(200);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//如果读取蓝牙RSSi回调成功
if(mBluetoothLeService.getRssiVal()){
//获取已经读到的RSSI值
Rssi=BluetoothLeService.getBLERSSI();
mHandler.obtainMessage(READRSSI, Rssi).sendToTarget();
}
}
}
};