我看了几个文章,主要是接受配对广播,然后设置pin,实现配对,但是网上的大部分手机是不可以的,android.bluetoothdevice 下 action_pair_request ,没有定义这个,开始困扰了我一点时间,实现难度:是否能进入那个广播响应。
定义了一个类,这个是网上的可以直接用
//================================================================================================================================
- package zicox.esc;
-
- import java.lang.reflect.Method;
- import java.lang.reflect.Field;
-
-
- import android.bluetooth.BluetoothAdapter;
- import android.bluetooth.BluetoothDevice;
- import android.util.Log;
-
- public class ClsUtils
- {
-
-
-
-
- static public boolean createBond(Class btClass, BluetoothDevice btDevice)
- throws Exception
- {
- Method createBondMethod = btClass.getMethod("createBond");
- Boolean returnValue = (Boolean) createBondMethod.invoke(btDevice);
- return returnValue.booleanValue();
- }
-
-
-
-
-
- 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)
- {
-
- e.printStackTrace();
- }
- catch (IllegalArgumentException e)
- {
-
- e.printStackTrace();
- }
- catch (Exception e)
- {
-
- e.printStackTrace();
- }
- return true;
-
- }
-
-
- static public boolean cancelPairingUserInput(Class btClass,
- BluetoothDevice device)
-
- throws Exception
- {
- Method createBondMethod = btClass.getMethod("cancelPairingUserInput");
-
- 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();
- }
-
-
-
-
-
- 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)
- {
-
- e.printStackTrace();
- }
- catch (IllegalArgumentException e)
- {
-
- e.printStackTrace();
- }
- catch (Exception e)
- {
-
- e.printStackTrace();
- }
- }
-
-
- static public boolean pair(String strAddr, String strPsw)
- {
- boolean result = false;
- BluetoothAdapter bluetoothAdapter = BluetoothAdapter
- .getDefaultAdapter();
-
- bluetoothAdapter.cancelDiscovery();
-
- if (!bluetoothAdapter.isEnabled())
- {
- bluetoothAdapter.enable();
- }
-
- if (!BluetoothAdapter.checkBluetoothAddress(strAddr))
- {
-
- Log.d("mylog", "devAdd un effient!");
- }
-
- BluetoothDevice device = bluetoothAdapter.getRemoteDevice(strAddr);
-
- if (device.getBondState() != BluetoothDevice.BOND_BONDED)
- {
- try
- {
- Log.d("mylog", "NOT BOND_BONDED");
- ClsUtils.setPin(device.getClass(), device, strPsw);
- ClsUtils.createBond(device.getClass(), device);
-
- result = true;
- }
- catch (Exception e)
- {
-
-
- Log.d("mylog", "setPiN failed!");
- e.printStackTrace();
- }
-
- }
- else
- {
- Log.d("mylog", "HAS BOND_BONDED");
- try
- {
- ClsUtils.createBond(device.getClass(), device);
- ClsUtils.setPin(device.getClass(), device, strPsw);
- ClsUtils.createBond(device.getClass(), device);
-
- result = true;
- }
- catch (Exception e)
- {
-
- Log.d("mylog", "setPiN failed!");
- e.printStackTrace();
- }
- }
- return result;
- }
- }
//================================================================================================================================
还有一部分 activity
//================================================================================================================================
- package zicox.esc;
-
- import java.io.IOException;
- import java.io.UnsupportedEncodingException;
- import java.lang.reflect.Method;
- import java.util.ArrayList;
- import java.util.List;
- import java.util.UUID;
-
- 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.content.IntentFilter;
- import android.os.Bundle;
- import android.util.Log;
- import android.view.View;
- import android.widget.AdapterView;
- import android.widget.ArrayAdapter;
- import android.widget.Button;
- import android.widget.ListView;
- import android.widget.Toast;
- import android.widget.ToggleButton;
-
-
- public class Demo_ad_escActivity extends Activity
- {
-
- public static String ErrorMessage;
- Button btnSearch, btnDis, btnExit;
- ToggleButton tbtnSwitch;
- ListView lvBTDevices;
- ArrayAdapter<String> adtDevices;
- List<String> lstDevices = new ArrayList<String>();
- BluetoothAdapter btAdapt;
- public static BluetoothSocket btSocket;
-
-
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
-
- Button Button1 = (Button) findViewById(R.id.button1);
- ErrorMessage = "";
-
-
- btnSearch = (Button) this.findViewById(R.id.btnSearch);
- btnSearch.setOnClickListener(new ClickEvent());
- btnExit = (Button) this.findViewById(R.id.btnExit);
- btnExit.setOnClickListener(new ClickEvent());
- btnDis = (Button) this.findViewById(R.id.btnDis);
- btnDis.setOnClickListener(new ClickEvent());
-
- tbtnSwitch = (ToggleButton) this.findViewById(R.id.toggleButton1);
- tbtnSwitch.setOnClickListener(new ClickEvent());
-
- lvBTDevices = (ListView) this.findViewById(R.id.listView1);
- adtDevices = new ArrayAdapter<String>(this,
- android.R.layout.simple_list_item_1, lstDevices);
- lvBTDevices.setAdapter(adtDevices);
- lvBTDevices.setOnItemClickListener(new ItemClickEvent());
-
- btAdapt = BluetoothAdapter.getDefaultAdapter();
-
- if (btAdapt.isEnabled())
- tbtnSwitch.setChecked(false);
- else
- tbtnSwitch.setChecked(true);
-
-
- String ACTION_PAIRING_REQUEST = "android.bluetooth.device.action.PAIRING_REQUEST";
- IntentFilter intent = new IntentFilter();
- intent.addAction(BluetoothDevice.ACTION_FOUND);
- intent.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
- intent.addAction(ACTION_PAIRING_REQUEST);
- intent.addAction(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED);
- intent.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
- registerReceiver(searchDevices, intent);
-
- Button1.setOnClickListener(new Button.OnClickListener()
- {
- public void onClick(View arg0)
- {
-
- }
- });
- }
-
-
-
- private BroadcastReceiver searchDevices = new BroadcastReceiver() {
-
- public void onReceive(Context context, Intent intent) {
- String action = intent.getAction();
- Bundle b = intent.getExtras();
- Object[] lstName = b.keySet().toArray();
-
-
- for (int i = 0; i < lstName.length; i++) {
- String keyName = lstName[i].toString();
- Log.e(keyName, String.valueOf(b.get(keyName)));
- }
- BluetoothDevice device = null;
-
- if (BluetoothDevice.ACTION_FOUND.equals(action)) {
- device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
- if (device.getBondState() == BluetoothDevice.BOND_NONE) {
- String str = "未配对|" + device.getName() + "|"
- + device.getAddress();
- if (lstDevices.indexOf(str) == -1)
- lstDevices.add(str);
- adtDevices.notifyDataSetChanged();
-
-
- try {
- ClsUtils.setPin(device.getClass(),device,"0000");
- } catch (Exception e) {
-
- e.printStackTrace();
- }
- try {
- ClsUtils.cancelPairingUserInput(device.getClass(), device);
- } catch (Exception e) {
-
- e.printStackTrace();
- }
-
- }
- }else if(BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)){
- device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
- switch (device.getBondState()) {
- case BluetoothDevice.BOND_BONDING:
- Log.d("BlueToothTestActivity", "正在配对......");
- break;
- case BluetoothDevice.BOND_BONDED:
- Log.d("BlueToothTestActivity", "完成配对");
- connect(device);
- break;
- case BluetoothDevice.BOND_NONE:
- Log.d("BlueToothTestActivity", "取消配对");
- default:
- break;
- }
- }
-
-
- if (intent.getAction().equals("android.bluetooth.device.action.PAIRING_REQUEST"))
- {
-
- Log.e("tag11111111111111111111111", "ddd");
- BluetoothDevice btDevice = intent
- .getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
-
-
-
-
- try
- {
- ClsUtils.setPin(btDevice.getClass(), btDevice, "0000");
- ClsUtils.createBond(btDevice.getClass(), btDevice);
- ClsUtils.cancelPairingUserInput(btDevice.getClass(), btDevice);
- }
- catch (Exception e)
- {
-
- e.printStackTrace();
- }
- }
- }
- };
-
- class ItemClickEvent implements AdapterView.OnItemClickListener {
-
- @Override
- public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
- long arg3) {
- if(btAdapt.isDiscovering())btAdapt.cancelDiscovery();
- String str = lstDevices.get(arg2);
- String[] values = str.split("\\|");
- String address = values[2];
- Log.e("address", values[2]);
- BluetoothDevice btDev = btAdapt.getRemoteDevice(address);
- try {
- Boolean returnValue = false;
- if (btDev.getBondState() == BluetoothDevice.BOND_NONE) {
-
-
-
-
- ClsUtils.pair(address, "0000");
- showMessage("here");
- }else if(btDev.getBondState() == BluetoothDevice.BOND_BONDED){
- connect(btDev);
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
-
- private void connect(BluetoothDevice btDev) {
- final UUID SPP_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
- UUID uuid = SPP_UUID;
- try {
- btSocket = btDev.createRfcommSocketToServiceRecord(uuid);
- Log.d("BlueToothTestActivity", "开始连接...");
- btSocket.connect();
- } catch (IOException e) {
-
- e.printStackTrace();
- }
- }
-
- class ClickEvent implements View.OnClickListener {
- @Override
- public void onClick(View v) {
- if (v == btnSearch)
- {
- if (btAdapt.getState() == BluetoothAdapter.STATE_OFF) {
- Toast.makeText(Demo_ad_escActivity.this, "请先打开蓝牙", 1000).show(); return;
- }
- if (btAdapt.isDiscovering())
- btAdapt.cancelDiscovery();
- lstDevices.clear();
- Object[] lstDevice = btAdapt.getBondedDevices().toArray();
- for (int i = 0; i < lstDevice.length; i++) {
- BluetoothDevice device = (BluetoothDevice) lstDevice[i];
- String str = "已配对|" + device.getName() + "|"
- + device.getAddress();
- lstDevices.add(str);
- adtDevices.notifyDataSetChanged();
- }
- setTitle("本机蓝牙地址:" + btAdapt.getAddress());
- btAdapt.startDiscovery();
- } else if (v == tbtnSwitch) {
- if (tbtnSwitch.isChecked() == false)
- btAdapt.enable();
-
- else if (tbtnSwitch.isChecked() == true)
- btAdapt.disable();
- } else if (v == btnDis)
- {
- Intent discoverableIntent = new Intent(
- BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
- discoverableIntent.putExtra(
- BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
- startActivity(discoverableIntent);
- } else if (v == btnExit) {
- try {
- if (btSocket != null)
- btSocket.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- Demo_ad_escActivity.this.finish();
- }
- }
- }
-
- @Override
- protected void onDestroy() {
- this.unregisterReceiver(searchDevices);
- super.onDestroy();
- android.os.Process.killProcess(android.os.Process.myPid());
- }
- public void showMessage(String str)
- {
- Toast.makeText(this,str, Toast.LENGTH_LONG).show();
- }
-
- }
//===================================================================================================
|