Android蓝牙连接FT232单片机
来源:互联网 发布:ubuntu卸载samba 编辑:程序博客网 时间:2024/06/04 22:17
刚上班,因为工作需要实现蓝牙连接单片机,一直没接触过蓝牙并且还是个初学者。在网上各种找,也终于实现了连接发送的功能。
代码写的太乱,什么也没考虑,好多都是其他网上的前辈的代码,有些还不明白。主要是想,哪位看见了指导一下。谢谢各位
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.activity_search); //注册连接的广播 registerReceiver(mGattUpdateReceiver, makeGattUpdateIntentFilter()); IntentFilter filter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED); registerReceiver(receiver, filter); startService(new Intent(this, BluetoothLeService.class)); initView(); } @Override protected void onStart() { super.onStart(); bindService(new Intent(this, BluetoothLeService.class), mServiceConnection, Context.BIND_AUTO_CREATE); } /** * 初始化布局 */ public void initView() { rippleBackground=(RippleBackground)findViewById(R.id.content); list = new ArrayList<>(); mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); tvSwitch = (TextView) findViewById(R.id.searchs_btn_title_switch); imgSearch = (ImageView) findViewById(R.id.searchs_img_search_png); tvSearch = (TextView) findViewById(R.id.searchs_tv_search_text); listView = (ListView) findViewById(R.id.searchs_lv); listView.setVerticalScrollBarEnabled(false); imgBack=(ImageView) findViewById(R.id.searchs_img_title_back); relativeLayout = (RelativeLayout) findViewById(R.id.searchs_rl_search_son); relativeLayout.setOnClickListener(this); imgBack.setOnClickListener(this); tvSwitch.setOnClickListener(this); devicesListAdapter = new DevicesListAdapter<>(this, list); listView.setAdapter(devicesListAdapter); listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { //点击条目进行连接 mBluetoothLeService.connect(list.get(position).getBluetoothAddress()); } }); } private IntentFilter makeGattUpdateIntentFilter() { //注册接收的事件 final IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction(BluetoothLeService.ACTION_GATT_CONNECTED); intentFilter.addAction(BluetoothLeService.ACTION_GATT_DISCONNECTED); intentFilter.addAction(BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED); intentFilter.addAction(BluetoothLeService.ACTION_DATA_AVAILABLE); intentFilter.addAction(BluetoothDevice.ACTION_UUID); return intentFilter; } @Override public void onClick(View v) { switch (v.getId()) { case R.id.searchs_btn_title_switch://开关蓝牙按钮 switchBluetooth(); break; case R.id.searchs_rl_search_son://搜索按钮 searchOnClick(); break; case R.id.searchs_img_title_back: finish(); break; } } /** * 开关蓝牙的方法 */ public void switchBluetooth() { if (mController.getBluetoothStatus()) { if (mBluetoothAdapter != null && mBluetoothAdapter.isEnabled()) { mBluetoothAdapter.disable(); isSearch = false; mBluetoothAdapter.cancelDiscovery();//关闭搜索 imgSearch.setImageResource(R.mipmap.sousuo); tvSearch.setText("搜索"); rippleBackground.stopRippleAnimation(); } } else { startActivityForResult(new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE), 1); } } /** * 点击搜索的方法 */ public void searchOnClick() { if (!mBluetoothAdapter.isEnabled()) { Toast.makeText(getApplicationContext(), "请先开启蓝牙", Toast.LENGTH_SHORT).show(); } else { if (isSearch) { rippleBackground.stopRippleAnimation(); isSearch = false; mBluetoothAdapter.cancelDiscovery();//关闭搜索 imgSearch.setImageResource(R.mipmap.sousuo); tvSearch.setText("搜索"); } else { rippleBackground.startRippleAnimation(); isSearch = true; imgSearch.setImageResource(R.mipmap.stop); tvSearch.setText("停止"); listView.setVisibility(View.VISIBLE); if (list != null) { list.clear(); if (devicesListAdapter != null) { devicesListAdapter.notifyDataSetChanged();//刷新 } } //开始搜索 mBluetoothAdapter.startDiscovery(); //注册搜索广播进行监听 IntentFilter filters = new IntentFilter(BluetoothDevice.ACTION_FOUND); registerReceiver(receiverss, filters); } } } /** * 搜索的广播监听 */ private BroadcastReceiver receiverss = new BroadcastReceiver() { public void onReceive(Context context, Intent intent) { String action = intent.getAction(); //搜索设备时,取得设备的MAC地址 if (BluetoothDevice.ACTION_FOUND.equals(action)) { BluetoothDevice device = intent .getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); //把蓝牙信息存到实体类中 blueToothBean = new BlueToothBean(device.getBluetoothClass().getDeviceClass(), device.getName(), false, device.getAddress()); boolean zai=false; if(list.size()>0) { for (int i = 0; i < list.size(); i++) { if (list.get(i).getBluetoothAddress().indexOf(blueToothBean.getBluetoothAddress())!=-1) { zai=true; } } if(!zai){ list.add(blueToothBean); } }else{ list.add(blueToothBean); } if (devicesListAdapter != null) { devicesListAdapter.notifyDataSetChanged(); } } } }; /** * 监听蓝牙的状态 */ private BroadcastReceiver receiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, 1); switch (state) { case BluetoothAdapter.STATE_OFF: tvSwitch.setText("开启"); isSearch = false; mBluetoothAdapter.cancelDiscovery();//关闭搜索 imgSearch.setImageResource(R.mipmap.sousuo); tvSearch.setText("搜索"); break; case BluetoothAdapter.STATE_ON: tvSwitch.setText("关闭"); break; case BluetoothAdapter.STATE_TURNING_ON:// Toast.makeText(SearchActivity.this, "正在打开蓝牙", Toast.LENGTH_SHORT).show(); break; case BluetoothAdapter.STATE_TURNING_OFF:// Toast.makeText(SearchActivity.this, "正在关闭蓝牙", Toast.LENGTH_SHORT).show(); break; default:// Toast.makeText(SearchActivity.this, "未知状态", Toast.LENGTH_SHORT).show(); } } }; private void ShowDialog() { Toast.makeText(this, "连接成功", Toast.LENGTH_SHORT).show(); } private final ServiceConnection mServiceConnection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName componentName, IBinder service) { mBluetoothLeService = ((BluetoothLeService.LocalBinder) service).getService(); if (!mBluetoothLeService.initialize()) { finish(); } } @Override public void onServiceDisconnected(ComponentName componentName) { mBluetoothLeService = null; } }; /** * 连接设备的广播监听 */ private final BroadcastReceiver mGattUpdateReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { final String action = intent.getAction(); if (BluetoothLeService.ACTION_GATT_CONNECTED.equals(action)) { Log.e(TAG, "Only gatt, just wait"); } else if (BluetoothLeService.ACTION_GATT_DISCONNECTED.equals(action)) { //断开连接 mConnected = false; invalidateOptionsMenu(); } else if (BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED.equals(action)) {//发送数据 mConnected = true; ShowDialog(); //发送信息 mBluetoothLeService.WriteValue("7E 7E 3D 3D"); invalidateOptionsMenu(); } else if (BluetoothLeService.ACTION_DATA_AVAILABLE.equals(action)) { //接收数据 //接收到byte数组类型的信息 byte[] bytes = intent.getByteArrayExtra(BluetoothLeService.EXTRA_DATA); //把信息转换成String类型 String sss = bytes2hex02(bytes); } } }; /** * byte[]转换成String方法 * * @param bytes * @return */ public String bytes2hex02(byte[] bytes) { StringBuilder sb = new StringBuilder(); String tmp = null; for (byte b : bytes) { // 将每个字节与0xFF进行与运算,然后转化为10进制,然后借助于Integer再转化为16进制 tmp = Integer.toHexString(0xFF & b); if (tmp.length() == 1)// 每个字节8为,转为16进制标志,2个16进制位 { tmp = "0" + tmp; } sb.append(tmp); } return sb.toString(); } @Override protected void onResume() { super.onResume(); //判断蓝牙是否开启 if (mController.getBluetoothStatus()) { tvSwitch.setText("关闭"); } else { tvSwitch.setText("开启"); } } @Override protected void onPause() { super.onPause(); } @Override protected void onStop() { super.onStop(); } @Override protected void onDestroy() { super.onDestroy(); unregisterReceiver(mGattUpdateReceiver); unbindService(mServiceConnection); mBluetoothAdapter.cancelDiscovery(); }
服务是主要代码 都是扒过来的,做了一丁点改动。
package com.example.hello.bluetoothdemo;import android.app.Service;import android.bluetooth.BluetoothAdapter;import android.bluetooth.BluetoothDevice;import android.bluetooth.BluetoothGatt;import android.bluetooth.BluetoothGattCallback;import android.bluetooth.BluetoothGattCharacteristic;import android.bluetooth.BluetoothGattDescriptor;import android.bluetooth.BluetoothGattService;import android.bluetooth.BluetoothManager;import android.bluetooth.BluetoothProfile;import android.content.Context;import android.content.Intent;import android.os.Binder;import android.os.IBinder;import android.util.Log;import java.util.List;import java.util.UUID;/** * */public class BluetoothLeService extends Service { private final static String TAG = BluetoothLeService.class.getSimpleName(); private BluetoothManager mBluetoothManager; private BluetoothAdapter mBluetoothAdapter; private BluetoothGatt mBluetoothGatt; public final static String ACTION_GATT_CONNECTED = "com.example.bluetooth.le.ACTION_GATT_CONNECTED"; public final static String ACTION_GATT_DISCONNECTED = "com.example.bluetooth.le.ACTION_GATT_DISCONNECTED"; public final static String ACTION_GATT_SERVICES_DISCOVERED = "com.example.bluetooth.le.ACTION_GATT_SERVICES_DISCOVERED"; public final static String ACTION_DATA_AVAILABLE = "com.example.bluetooth.le.ACTION_DATA_AVAILABLE"; public final static String EXTRA_DATA = "com.example.bluetooth.le.EXTRA_DATA"; public final static UUID UUID_NOTIFY = UUID.fromString("0000ffe1-0000-1000-8000-00805f9b34fb"); public final static UUID UUID_SERVICE = UUID.fromString("0000ffe0-0000-1000-8000-00805f9b34fb"); public BluetoothGattCharacteristic mNotifyCharacteristic; /** * 向单片机中发送信息 十六进制 * @param strValue */ public void WriteValue(String strValue) { mNotifyCharacteristic.setValue(toByteArray(strValue)); mBluetoothGatt.writeCharacteristic(mNotifyCharacteristic); } /** * 转换 * @param arg * @return */ public static byte[] toByteArray(String arg) { if (arg != null) {/* 1.先去除String中的' ',然后将String转换为char数组 */ char[] NewArray = new char[1000]; char[] array = arg.toCharArray(); int length = 0; for (int i = 0; i < array.length; i++) { if (array[i] != ' ') { NewArray[length] = array[i]; length++; } }/* 将char数组中的值转成一个实际的十进制数组 */ int EvenLength = (length % 2 == 0) ? length : length + 1; if (EvenLength != 0) { int[] data = new int[EvenLength]; data[EvenLength - 1] = 0; for (int i = 0; i < length; i++) { if (NewArray[i] >= '0' && NewArray[i] <= '9') { data[i] = NewArray[i] - '0'; } else if (NewArray[i] >= 'a' && NewArray[i] <= 'f') { data[i] = NewArray[i] - 'a' + 10; } else if (NewArray[i] >= 'A' && NewArray[i] <= 'F') { data[i] = NewArray[i] - 'A' + 10; } }/* 将 每个char的值每两个组成一个16进制数据 */ byte[] byteArray = new byte[EvenLength / 2]; for (int i = 0; i < EvenLength / 2; i++) { byteArray[i] = (byte) (data[i * 2] * 16 + data[i * 2 + 1]); } return byteArray; } } return new byte[] {}; } public void findService(List<BluetoothGattService> gattServices) { Log.i(TAG, "Count is:" + gattServices.size()); for (BluetoothGattService gattService : gattServices) { Log.i(TAG, gattService.getUuid().toString());Log.i(TAG, UUID_SERVICE.toString()); if(gattService.getUuid().toString().equalsIgnoreCase(UUID_SERVICE.toString())) { List<BluetoothGattCharacteristic> gattCharacteristics = gattService.getCharacteristics(); Log.i(TAG, "Count is:" + gattCharacteristics.size()); for (BluetoothGattCharacteristic gattCharacteristic : gattCharacteristics) { if(gattCharacteristic.getUuid().toString().equalsIgnoreCase(UUID_NOTIFY.toString())) { Log.i(TAG, gattCharacteristic.getUuid().toString()); Log.i(TAG, UUID_NOTIFY.toString()); mNotifyCharacteristic = gattCharacteristic; setCharacteristicNotification(gattCharacteristic, true); broadcastUpdate(ACTION_GATT_SERVICES_DISCOVERED); return; } } } } } private final BluetoothGattCallback mGattCallback = new BluetoothGattCallback() { @Override public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) { String intentAction; Log.i(TAG, "oldStatus=" + status + " NewStates=" + newState); if(status == BluetoothGatt.GATT_SUCCESS) { if (newState == BluetoothProfile.STATE_CONNECTED) { intentAction = ACTION_GATT_CONNECTED; broadcastUpdate(intentAction); Log.i(TAG, "Connected to GATT server."); // Attempts to discover services after successful connection. Log.i(TAG, "Attempting to start service discovery:" + mBluetoothGatt.discoverServices()); } else if (newState == BluetoothProfile.STATE_DISCONNECTED) { intentAction = ACTION_GATT_DISCONNECTED; mBluetoothGatt.close(); mBluetoothGatt = null; Log.i(TAG, "Disconnected from GATT server."); broadcastUpdate(intentAction); } } } @Override public void onServicesDiscovered(BluetoothGatt gatt, int status) { if (status == BluetoothGatt.GATT_SUCCESS) { Log.w(TAG, "onServicesDiscovered received: " + status); findService(gatt.getServices()); } else { if(mBluetoothGatt.getDevice().getUuids() == null) Log.w(TAG, "onServicesDiscovered received: " + status); } } @Override public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) { if (status == BluetoothGatt.GATT_SUCCESS) { broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic); } } @Override public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) { broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic); Log.e(TAG, "OnCharacteristicWrite"); } @Override public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) { Log.e(TAG, "OnCharacteristicWrite"); } @Override public void onDescriptorRead(BluetoothGatt gatt, BluetoothGattDescriptor bd, int status) { Log.e(TAG, "onDescriptorRead"); } @Override public void onDescriptorWrite(BluetoothGatt gatt, BluetoothGattDescriptor bd, int status) { Log.e(TAG, "onDescriptorWrite"); } @Override public void onReadRemoteRssi(BluetoothGatt gatt, int a, int b) { Log.e(TAG, "onReadRemoteRssi"); } @Override public void onReliableWriteCompleted(BluetoothGatt gatt, int a) { Log.e(TAG, "onReliableWriteCompleted"); } }; private void broadcastUpdate(final String action) { final Intent intent = new Intent(action); sendBroadcast(intent); } private void broadcastUpdate(final String action, final BluetoothGattCharacteristic characteristic) { final Intent intent = new Intent(action); final byte[] data = characteristic.getValue(); if (data != null && data.length > 0) { intent.putExtra(EXTRA_DATA, data); } sendBroadcast(intent); } public class LocalBinder extends Binder { public BluetoothLeService getService() { return BluetoothLeService.this; } } @Override public IBinder onBind(Intent intent) { return mBinder; } @Override public boolean onUnbind(Intent intent) { close(); return super.onUnbind(intent); } private final IBinder mBinder = new LocalBinder(); public boolean initialize() { if (mBluetoothManager == null) { mBluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE); if (mBluetoothManager == null) { Log.e(TAG, "Unable to initialize BluetoothManager."); return false; } } mBluetoothAdapter = mBluetoothManager.getAdapter(); if (mBluetoothAdapter == null) { Log.e(TAG, "Unable to obtain a BluetoothAdapter."); return false; } return true; } public boolean connect(final String address) { if (mBluetoothAdapter == null || address == null) { Log.w(TAG, "BluetoothAdapter not initialized or unspecified address."); return false; } BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address); if (device == null) { Log.w(TAG, "Device not found. Unable to connect."); return false; } if(mBluetoothGatt != null) { mBluetoothGatt.close(); mBluetoothGatt = null; } mBluetoothGatt = device.connectGatt(this, false, mGattCallback); Log.d(TAG, "Trying to create a new connection."); return true; } public void disconnect() { if (mBluetoothAdapter == null || mBluetoothGatt == null) { Log.w(TAG, "BluetoothAdapter not initialized"); return; } mBluetoothGatt.disconnect(); } public void close() { if (mBluetoothGatt == null) { return; } mBluetoothGatt.close(); mBluetoothGatt = null; } public void readCharacteristic(BluetoothGattCharacteristic characteristic) { if (mBluetoothAdapter == null || mBluetoothGatt == null) { Log.w(TAG, "BluetoothAdapter not initialized"); return; } mBluetoothGatt.readCharacteristic(characteristic); } public void setCharacteristicNotification(BluetoothGattCharacteristic characteristic, boolean enabled) { if (mBluetoothAdapter == null || mBluetoothGatt == null) { Log.w(TAG, "BluetoothAdapter not initialized"); return; } mBluetoothGatt.setCharacteristicNotification(characteristic, enabled); } public List<BluetoothGattService> getSupportedGattServices() { if (mBluetoothGatt == null) return null; return mBluetoothGatt.getServices(); }}
public class BluetoothController { private BluetoothAdapter mAdapter; public BluetoothController(){ mAdapter = BluetoothAdapter.getDefaultAdapter(); } /** * 判断当前设备是否支持蓝牙 * @return */ public boolean isSupportBluetooth(){ if(mAdapter!=null){ return true; } return false; } /** * 获取蓝牙的状态 * @return */ public boolean getBluetoothStatus(){ if(mAdapter!=null){ return mAdapter.isEnabled(); } return false; } /** * 打开蓝牙 * @param activity * @param requestCode */ public void turnOnBluetooth(Activity activity, int requestCode){ if(mAdapter!=null&&!mAdapter.isEnabled()) { Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); activity.startActivityForResult(intent, requestCode); } } /** * 关闭蓝牙 */ public void turnOffBluetooth(){ if(mAdapter!=null&&mAdapter.isEnabled()) { mAdapter.disable(); } }}
大神们 我需要你们的批斗,我欠缺经验,请多指导。
阅读全文
0 0
- Android蓝牙连接FT232单片机
- [Android蓝牙]------连接蓝牙流程
- 蓝牙4.0连接单片机心得分享
- android蓝牙串口连接
- Android 蓝牙连接实现
- android 之连接蓝牙
- Android 蓝牙连接问题
- Android蓝牙设置连接
- Android蓝牙串口连接
- android 蓝牙模块连接
- Android蓝牙连接打印
- Android连接蓝牙4.0
- Android连接经典蓝牙
- android连接蓝牙音响
- Android手机蓝牙与单片机蓝牙串通信开发经验总结
- android手机蓝牙连接蓝牙设备
- Android蓝牙连接远程蓝牙事例
- 蓝牙连接MSP430F1232单片机之后,不传输数据
- 自动注册/proc文件
- Android Studio 彻底断开于SVN的连接
- 二叉树遍历
- HBase Thrift
- PAT B1001. 害死人不偿命的(3n+1)猜想
- Android蓝牙连接FT232单片机
- IAR for ARM介绍、下载、安装与注册
- js实现图片上传预览(一张一张上传)
- extjs问题1
- 刷题记录-luoguP1991 无线通讯网
- Windows系统下如何配置虚拟域名 Apache服务器
- 总结--安装linux测试环境
- 盘点四种保密电脑照片的方法
- UVA 253 枚举