Android蓝牙BLE之RSSI读写(2)

第二种方法就是连接后读取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();
				}
				
			}
			
		}
		
	};

源码在 在 http://download.csdn.net/detail/mapeifan/9355353

你可能感兴趣的:(bluetooth)