`
不夜的星辰
  • 浏览: 88553 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类
最新评论

android bluetooth

 
阅读更多
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;
	}
}

 

分享到:
评论
1 楼 yandol 2013-07-31  
ClsUtils 是个什么库的函数啊,看起来挺好用的,nj.com没有相关信息啊

相关推荐

    Android Bluetooth OPP Bugreport

    在Android系统中,Bluetooth OPP(Object Push Profile)是一种用于设备间传输小文件的协议,它允许用户方便地发送图片、联系人、日历事件等数据。这篇博客文章的附件是针对一个特定的Android设备(可能是Xiaomi设备...

    Android Bluetooth

    在Android系统中,蓝牙(Bluetooth)技术是一种广泛用于设备间短距离无线通信的协议,它允许不同的设备如手机、电脑、耳机、打印机等互相连接,交换数据或进行媒体播放。本篇文章将深入探讨如何在Android平台上支持...

    Android bluetooth

    在Android系统中,蓝牙(Bluetooth)技术是一种广泛用于设备间无线通信的标准,它允许设备进行数据交换和配对,例如连接耳机、智能手表、车载音响等。本篇将深入探讨在Android蓝牙开发过程中可能遇到的问题及如何...

    Android BlueTooth 4.0 案例

    在Android平台上,Bluetooth 4.0,也称为Bluetooth Low Energy (BLE) 或 Bluetooth Smart,是一种高效、低功耗的无线通信技术,广泛应用于健康监测、智能家居、运动追踪等物联网(IoT)设备。本案例“Android ...

    android bluetooth框架知识

    Android Bluetooth 框架知识 Android Bluetooth 框架知识是指在 Android 系统中,关于 Bluetooth 技术的架构和实现细节。Android 4.2 和 4.3 中的 Bluetooth 框架知识是特别重要的,因为在这个版本中,Android 引入...

    android bluetooth framework,application 层分析

    AndroidBluetooth Framework 是 Android 操作系统中的蓝牙协议栈,负责管理蓝牙设备的连接、数据传输和蓝牙 Profile 的管理。整个蓝牙系统可以分为四个层次:蓝牙嵌入式系统(BTE)、蓝牙应用(BTA)、蓝牙系统服务...

Global site tag (gtag.js) - Google Analytics