package com.nj.bluetooth; import java.io.DataInputStream; import java.io.IOException; import java.lang.reflect.Method; import java.util.UUID; import android.app.Service; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothSocket; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.os.AsyncTask; import android.os.Handler; import android.os.IBinder; import android.os.Message; import android.util.Log; import android.widget.Toast; import com.nj.activity.task.TaskMainActivity; import com.nj.activity.task.collect.ScanDataActivity; import com.nj.activity.task.match.CheckDataActivity; import com.nj.deamon.HandlerManager; import com.nj.tool.ClsUtils; import com.nj.tool.Constant; import com.nj.activity.BlueToothTestActivity; public class BlueToothService extends Service { public static BluetoothDevice device; private BluetoothSocket socket; public static boolean isConnect = false; private boolean isRuning = true; private SharedPreferences sPreferences; @Override public IBinder onBind(Intent intent) { // TODO Auto-generated method stub return null; } @Override public void onCreate() { super.onCreate(); } @Override public void onStart(Intent intent, int startId) { // TODO Auto-generated method stub super.onStart(intent, startId); sPreferences = getSharedPreferences(Constant.PREFERENCES_NAME, MODE_WORLD_READABLE | MODE_WORLD_WRITEABLE); if(intent != null){ device = intent.getParcelableExtra("blueDevice"); } if(device != null){ /** * 自动设置匹配码 */ boolean result = ClsUtils.pair(device.getAddress(), "0000", BluetoothAdapter.getDefaultAdapter()); if(!result){ ClsUtils.pair(device.getAddress(), "1234", BluetoothAdapter.getDefaultAdapter()); } new LinkBlueTooth().execute(device); }else{ Log.v("=======BlueToothService===device===", "="+device); } } @Override public void onDestroy() { // TODO Auto-generated method stub super.onDestroy(); if(socket != null){ try { socket.close(); } catch (IOException e) { e.printStackTrace(); } } device = null; isRuning = false; isConnect = false; } class LinkBlueTooth extends AsyncTask<Object, Void, Boolean>{ @Override protected void onPostExecute(Boolean result) { if(!result){ Message message = new Message(); message.what = Constant.LINK_FAILE; Handler handler = HandlerManager.getHandler(ScanDataActivity.class.getName()); if(handler != null){ message.obj = "主机已关"; handler.sendMessage(message); }else if(handler == null){ handler = HandlerManager.getHandler(CheckDataActivity.class.getName()); if(handler != null){ message.obj = "主机已关"; handler.sendMessage(message); }else { handler = HandlerManager.getHandler(BlueToothTestActivity.class.getName()); if(handler != null){ handler.sendMessage(message); }else{ handler = HandlerManager.getHandler(TaskMainActivity.class.getName()); if(handler != null){ handler.sendMessage(message); } } } } } super.onPostExecute(result); } @Override protected Boolean doInBackground(Object... params) { BluetoothDevice device = (BluetoothDevice) params[0]; // Log.v("====device====", device.getName()); try { for(int i = 0;i < 3;i++){ /** * 获取蓝牙连接 */ Method method = device.getClass().getMethod("createRfcommSocket", new Class[]{int.class}); socket = (BluetoothSocket) method.invoke(device, 1); // socket = device.createRfcommSocketToServiceRecord(UUID.fromString("00001101-0000-1000-8000-00805F9B34FB")); socket.connect(); isConnect = true; Constant.lastBluetoothDevice = device; Editor editor = sPreferences.edit(); editor.putString(Constant.lastBlueDevice, device.getAddress()); editor.commit(); Message message = new Message(); message.what = Constant.LINK_SUCCESS; Handler handler = HandlerManager.getHandler(ScanDataActivity.class.getName()); if(handler != null){ handler.sendMessage(message); }else{ handler = HandlerManager.getHandler(CheckDataActivity.class.getName()); if(handler != null){ handler.sendMessage(message); }else{ handler = HandlerManager.getHandler(BlueToothTestActivity.class.getName()); if(handler != null){ handler.sendMessage(message); }else{ handler = HandlerManager.getHandler(TaskMainActivity.class.getName()); if(handler != null){ handler.sendMessage(message); } } } } readData(); break; } } catch (Exception e) { e.printStackTrace(); } return isConnect; } } /** * 读取数据 */ private void readData(){ DataInputStream dInputStream = null; Handler handle = null ; try { dInputStream = new DataInputStream(socket.getInputStream()); while (isRuning) { String data = dInputStream.readLine(); // Log.v("======================data===================", "data="+data); if(data == null || "".equals(data)){ continue; } handle = HandlerManager.getHandler(ScanDataActivity.class.getName()); // Log.v("======================handler===================", "handler="+handle); //传递给 盘点采集 界面 if(handle != null){ Message msg = handle.obtainMessage(); msg.what = ScanDataActivity.task_collect_scan_msg; msg.obj = data; handle.sendMessage(msg); } //传递给 数据对比 界面 handle = HandlerManager.getHandler(CheckDataActivity.class.getName()); if(handle != null){ Message msg = handle.obtainMessage(); msg.what = CheckDataActivity.task_checkData_scan_msg; msg.obj = data; handle.sendMessage(msg); } } } catch (Exception e) { Message message = new Message(); message.what = Constant.TASK_COLLECT_CLOSE_SCAN; Handler handler = HandlerManager.getHandler(ScanDataActivity.class.getName()); if(handler != null){ handler.sendMessage(message); }else{ handler = HandlerManager.getHandler(CheckDataActivity.class.getName()); if(handler != null){ handler.sendMessage(message); } } // message.what = com.nj.activity.BlueToothTestActivity.LINK_DISCON; // com.nj.activity.BlueToothTestActivity.handler.sendMessage(message); stopSelf(); }finally{ try { if(dInputStream != null){ dInputStream.close(); } } catch (Exception e2) { } } } }
package com.nj.tool; /*********************************** * 蓝牙配对函数 * **************/ import java.lang.reflect.Field; import java.lang.reflect.Method; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.util.Log; public class ClsUtils { /** * 涓庤澶囬厤瀵�鍙傝�婧愮爜锛歱latform/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(); } /** * 涓庤澶囪В闄ら厤瀵�鍙傝�婧愮爜锛歱latform/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 block e.printStackTrace(); } return true; } /** * * @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) { // TODO Auto-generated catch block e.printStackTrace(); } } /** * 配对 * @param address * @param psw * @return */ public static boolean pair(String address,String psw,BluetoothAdapter adapter){ boolean result = false; BluetoothDevice device = adapter.getRemoteDevice(address); if(device.getBondState() != BluetoothDevice.BOND_BONDED){ try { setPin(device.getClass(),device, psw); boolean flag = createBond(device.getClass(), device); if(flag){ result = true; } } catch (Exception e) { e.printStackTrace(); } }else { result = true; } return result; } }