蓝牙自动打开并配对

来源:互联网 发布:淘宝地区怎么修改 编辑:程序博客网 时间:2024/04/29 12:52
主程序:
import java.util.Set;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.os.Bundle;import android.os.Handler;import android.os.IBinder;import android.os.Message;import android.util.Log;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.TextView;import com.guide.bluetooth.ClsUtils;public class BluetoothActivity extends Activity {private String TAG = "BluetoothTest ";private static boolean noFound = true;private final static int MSG_BLUETOOTH_SCAN = 1;private Button skip;private TextView showpro;/* 取得默认的蓝牙适配器 */private BluetoothAdapter mBtAdapter = BluetoothAdapter.getDefaultAdapter();@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.bluetooth);if (!mBtAdapter.isEnabled()) {mBtAdapter.enable();Log.e(TAG, "bluetooth enable");}// 注册扫描广播IntentFilter discoveryFilter = new IntentFilter();discoveryFilter.addAction(BluetoothDevice.ACTION_FOUND);// discoveryFilter.addAction(BluetoothDevice.ACTION_FOUND);discoveryFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);this.registerReceiver(mReceiver, discoveryFilter);Set<BluetoothDevice> pairedDevices = mBtAdapter.getBondedDevices();// 打印已绑定设备if (pairedDevices.size() > 0) {for (BluetoothDevice device : pairedDevices) {Log.e(TAG + "------>", device.getName() + "\n" + device.getAddress());}} else {Log.e(TAG, "MEI YOU PEI DUI SHE BEI");}mhandler.sendEmptyMessageDelayed(MSG_BLUETOOTH_SCAN, 1000);skip = (Button) findViewById(R.id.skip);showpro=(TextView)findViewById(R.id.bluetooth);skip.setOnClickListener( new OnClickListener() {@Overridepublic void onClick(View arg0) {Intent intent = new Intent();intent.setClass(BluetoothActivity.this,GuideFirstNetworkActivity.class);startActivity(intent);finish();}});}private final BroadcastReceiver mReceiver = new BroadcastReceiver() {@Overridepublic void onReceive(Context context, Intent intent) {String action = intent.getAction();// When discovery finds a deviceif (BluetoothDevice.ACTION_FOUND.equals(action)) {// Get the BluetoothDevice object from the IntentBluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);// If it's already paired, skip it, because it's been listed// alreadyif (device.getBondState() != BluetoothDevice.BOND_BONDED) {if (device.getName().equals("HBG BLE REMOTE")) {try {ClsUtils.createBond(device.getClass(), device);// ClsUtils.cancelPairingUserInput(device.getClass(),// device);noFound = false;showpro.setText("恭喜!连接成功");Intent intentwire = new Intent();intentwire.setClass(context,GuideFirstNetworkActivity.class);startActivity(intentwire);} catch (Exception e) {e.printStackTrace();}Log.e(TAG,device.getName() + "\n" + device.getAddress());}// When discovery is finished, change the Activity title} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {if (noFound) {mBtAdapter.startDiscovery();Log.e(TAG, "device has not found");} else {noFound = false;mBtAdapter.cancelDiscovery();Log.e(TAG, "device has found");}}}}};@Overrideprotected void onResume() {mhandler.sendEmptyMessageDelayed(MSG_BLUETOOTH_SCAN, 1000);super.onResume();}@Overridepublic void onDestroy() {super.onDestroy();// Make sure we're not doing discovery anymoreif (mBtAdapter != null) {mBtAdapter.cancelDiscovery();}// Unregister broadcast listenersthis.unregisterReceiver(mReceiver);}Handler mhandler = new Handler() {@Overridepublic void handleMessage(Message msg) {// TODO Auto-generated method stubswitch (msg.what) {case MSG_BLUETOOTH_SCAN:doScan();if(noFound){mhandler.sendEmptyMessage(MSG_BLUETOOTH_SCAN);}break;default:super.handleMessage(msg);}}};private void doScan() {Log.e(TAG, "doscan...");showpro.setText("正在扫描蓝牙遥控器设备...");mBtAdapter.startDiscovery();}public IBinder onBind(Intent intent) {// TODO Auto-generated method stubreturn null;}}
ClsUtils.java
import java.lang.reflect.Field;import java.lang.reflect.Method;import android.bluetooth.BluetoothDevice;import android.util.Log;public class ClsUtils {/** * 与设备配对 参考源码:platform/packages/apps/Settings.git * /Settings/src/com/android/settings/bluetooth/CachedBluetoothDevice.java */static public boolean createBond(Class btClass, BluetoothDevice btDevice)throws Exception{Method createBondMethod = btClass.getMethod("createBond");Boolean returnValue = (Boolean) createBondMethod.invoke(btDevice);return returnValue.booleanValue();}/** * 与设备解除配对 参考源码:platform/packages/apps/Settings.git * /Settings/src/com/android/settings/bluetooth/CachedBluetoothDevice.java */static public boolean removeBond(Class btClass, BluetoothDevice btDevice)throws Exception{Method removeBondMethod = btClass.getMethod("removeBond");Boolean returnValue = (Boolean) removeBondMethod.invoke(btDevice);return returnValue.booleanValue();}static public boolean setPin(Class btClass, BluetoothDevice btDevice,String str) throws Exception{try{Method removeBondMethod = btClass.getDeclaredMethod("setPin",new Class[]{byte[].class});Boolean returnValue = (Boolean) removeBondMethod.invoke(btDevice,new Object[]{str.getBytes()});Log.e("returnValue", "" + returnValue);}catch (SecurityException e){// throw new RuntimeException(e.getMessage());e.printStackTrace();}catch (IllegalArgumentException e){// throw new RuntimeException(e.getMessage());e.printStackTrace();}catch (Exception e){// TODO Auto-generated catch blocke.printStackTrace();}return true;}// 取消用户输入static public boolean cancelPairingUserInput(Class btClass,BluetoothDevice device)throws Exception{Method createBondMethod = btClass.getMethod("cancelPairingUserInput");// cancelBondProcess()Boolean returnValue = (Boolean) createBondMethod.invoke(device);return returnValue.booleanValue();}// 取消配对static public boolean cancelBondProcess(Class btClass,BluetoothDevice device)throws Exception{Method createBondMethod = btClass.getMethod("cancelBondProcess");Boolean returnValue = (Boolean) createBondMethod.invoke(device);return returnValue.booleanValue();}/** *  * @param clsShow */static public void printAllInform(Class clsShow){try{// 取得所有方法Method[] hideMethod = clsShow.getMethods();int i = 0;for (; i < hideMethod.length; i++){Log.e("method name", hideMethod[i].getName() + ";and the i is:"+ i);}// 取得所有常量Field[] allFields = clsShow.getFields();for (i = 0; i < allFields.length; i++){Log.e("Field name", allFields[i].getName());}}catch (SecurityException e){// throw new RuntimeException(e.getMessage());e.printStackTrace();}catch (IllegalArgumentException e){// throw new RuntimeException(e.getMessage());e.printStackTrace();}catch (Exception e){e.printStackTrace();}}}
Bluetooth.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="fill_parent"    android:layout_height="fill_parent"    android:background="@drawable/bluetooth"    tools:context=".BluetoothActivity" >    <TextView        android:id="@+id/bluetooth"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_alignParentTop="true"        android:layout_centerHorizontal="true"        android:layout_marginTop="22dp"        android:textColor="@color/white"         android:textSize="40sp" />    <TextView        android:id="@+id/textView1"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_centerHorizontal="true"        android:layout_marginTop="80dp"        android:layout_marginLeft="100dp"        android:text="@string/pleaseback"        android:textColor="@color/white"        android:textSize="40sp" /></RelativeLayout>


0 0
原创粉丝点击