由于毕业设计用得到蓝牙,因此简单研究了一下蓝牙。由于本人学术知识有限,本文可能出现错误,请指正。

介绍一下

JDY-10M蓝牙模块:

手机系统为安卓9版本。

使用的工具为android studio3.5.(应该算是最新版本了),适配的安卓版本为安卓9(我手机的版本为安卓9)

买的JAY-10M附带的资料给了APP的源码,然后尝试了将这个源代码直接移植到我自己的项目中,出了问题。自带两个apk文件,一个闪退,另一个能够正常使用。源代码适配的是安卓5的。因此,这个源代码应该是没有问题的。查看报错,是权限的问题。但是已经再声明文件中给了蓝牙的权限,这是为什么呢?最后搞清楚了需要增加一个动态权限申请蓝牙权限后才能够正常使用。

这个硬件自带的直接控制硬件的删掉了,要自己焊,拆开比较麻烦(使用热缩套把贴片和底板锁在一起,就不拆了)

由于篇幅有限以及时间问题,功能上做了一些删减。

由于是使用旧版的示例代码,有些方法已经不推荐使用了,最新的方法也有,但是最官网上BLE的示例还是使用该方法实现的,后期有时间会写一下(别问为什么不用最新的,问就是不会,问就是英语不行,问就是懒)。

贴一下安卓蓝牙的手册(当然谷歌是纯英文的)

蓝牙概述

该APP有两个界面,第一个界面显示蓝牙扫描到的蓝牙设备名称、mac地址(有些蓝牙设备是没名字的,带mac地址保险点),第二个界面连接蓝牙设备进行控制。

扫描界面放一个listview。

假定名字为SCAN_VIEW.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:tools="http://schemas.android.com/tools"android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical"tools:context=".MainActivity" ><ListViewandroid:id="@+id/lv_bleList"android:layout_width="fill_parent"android:layout_height="fill_parent" /></LinearLayout>

创建一个layout(显示单条蓝牙信息)

用于显示蓝牙设备的名称和mac地址

假定名字为ITEM_BLE_LIST.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:orientation="vertical"android:layout_width="match_parent"android:layout_height="wrap_content"><TextView android:id="@+id/device_name"android:layout_width="match_parent"android:layout_height="wrap_content"android:textSize="25dp"/><TextView android:id="@+id/device_address"android:layout_width="match_parent"android:layout_height="wrap_content"android:textSize="15dp"/></LinearLayout>

扫描界面右上角设置按钮,用来扫描设备和停止扫描。

新建一个menu

假定名字为SCAN_MAIN.xml.

三个按钮分别为刷新中,扫描,停止扫描


<menu xmlns:android="http://schemas.android.com/apk/res/android"><item android:id="@+id/menu_refresh"android:checkable="false"android:orderInCategory="1"android:showAsAction="ifRoom"/><item android:id="@+id/menu_scan"android:title="@string/menu_scan"android:orderInCategory="100"android:showAsAction="ifRoom|withText"/><item android:id="@+id/menu_stop"android:title="@string/menu_stop"android:orderInCategory="101"android:showAsAction="ifRoom|withText"/></menu>

扫描界面代码:

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothAdapter.LeScanCallback;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;/*** Activity for scanning and displaying available Bluetooth LE devices.*/
public  class DeviceScanActivity extends Activity implements OnClickListener  {private BluetoothAdapter mBluetoothAdapter;private boolean mScanning;private Handler mHandler;private static final int REQUEST_ENABLE_BT = 1;// Stops scanning after 10 seconds.private static final long SCAN_PERIOD = 10000;private DeviceListAdapter mDevListAdapter;ToggleButton tb_on_off;TextView btn_searchDev;Button btn_aboutUs;ListView lv_bleList;Timer timer;@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);//getActionBar().setTitle(R.string.title_devices);mHandler = new Handler();// Use this check to determine whether BLE is supported on the device.  Then you can// selectively disable BLE-related features.if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {Toast.makeText(this, R.string.ble_not_supported, Toast.LENGTH_SHORT).show();finish();}// Initializes a Bluetooth adapter.  For API level 18 and above, get a reference to// BluetoothAdapter through BluetoothManager.final BluetoothManager bluetoothManager =(BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);mBluetoothAdapter = bluetoothManager.getAdapter();// Checks if Bluetooth is supported on the device.if (mBluetoothAdapter == null) {Toast.makeText(this, R.string.error_bluetooth_not_supported, Toast.LENGTH_SHORT).show();finish();return;}lv_bleList = (ListView) findViewById(R.id.lv_bleList);mDevListAdapter = new DeviceListAdapter();lv_bleList.setAdapter(mDevListAdapter);lv_bleList.setOnItemClickListener(new OnItemClickListener() {@Overridepublic void onItemClick(AdapterView<?> parent, View view,int position, long id) {if (mDevListAdapter.getCount() > 0) {  BluetoothDevice device1 = mDevListAdapter.getItem(position);if (device1 == null) return;Intent intent1 = new Intent(DeviceScanActivity.this,DeviceControlActivity.class);;intent1.putExtra(DeviceControlActivity.EXTRAS_DEVICE_NAME, device1.getName());intent1.putExtra(DeviceControlActivity.EXTRAS_DEVICE_ADDRESS, device1.getAddress());if (mScanning) {mBluetoothAdapter.stopLeScan(mLeScanCallback);mScanning = false;}startActivity(intent1);}}});}public void onClick(View v) {switch (v.getId()) {case 0:break;}}@Overridepublic boolean onCreateOptionsMenu(Menu menu) {getMenuInflater().inflate(R.menu.main, menu);if (!mScanning) {menu.findItem(R.id.menu_stop).setVisible(false);menu.findItem(R.id.menu_scan).setVisible(true);menu.findItem(R.id.menu_refresh).setActionView(null);} else {menu.findItem(R.id.menu_stop).setVisible(true);menu.findItem(R.id.menu_scan).setVisible(false);menu.findItem(R.id.menu_refresh).setActionView(R.layout.actionbar_indeterminate_progress);}return true;}@Overridepublic boolean onOptionsItemSelected(MenuItem item) {switch (item.getItemId()) {case R.id.menu_scan://mLeDeviceListAdapter.clear();scanLeDevice(true);//mDevListAdapter.;mDevListAdapter.clear();mDevListAdapter.notifyDataSetChanged();break;case R.id.menu_stop:scanLeDevice(false);break;}return true;}private void scanLeDevice(final boolean enable) {if (enable) {// Stops scanning after a pre-defined scan period.mHandler.postDelayed(new Runnable() {@Overridepublic void run() {mScanning = false;mBluetoothAdapter.stopLeScan(mLeScanCallback);invalidateOptionsMenu();}}, SCAN_PERIOD);mScanning = true;mBluetoothAdapter.startLeScan(mLeScanCallback);} else {mScanning = false;mBluetoothAdapter.stopLeScan(mLeScanCallback);}invalidateOptionsMenu();}private BluetoothAdapter.LeScanCallback mLeScanCallback = new LeScanCallback() {@Overridepublic void onLeScan(final BluetoothDevice device, int rssi,byte[] scanRecord) {runOnUiThread(new Runnable() {@Overridepublic void run() {mDevListAdapter.addDevice(device);mDevListAdapter.notifyDataSetChanged();}});}};@Overrideprotected void onResume() {//打开APP时扫描设备super.onResume();scanLeDevice(true);}@Overrideprotected void onPause() {//停止扫描super.onPause();scanLeDevice(false);}//自定义DeviceListAdapter类,用于显示数据,清除数据class DeviceListAdapter extends BaseAdapter {private List<BluetoothDevice> mBleArray;private ViewHolder viewHolder;public DeviceListAdapter() {mBleArray = new ArrayList<BluetoothDevice>();}public void addDevice(BluetoothDevice device) {if (!mBleArray.contains(device)) {mBleArray.add(device);}}public void clear(){mBleArray.clear();}@Overridepublic int getCount() {return mBleArray.size();}@Overridepublic BluetoothDevice getItem(int position) {return mBleArray.get(position);}@Overridepublic long getItemId(int position) {return position;}@Overridepublic View getView(int position, View convertView, ViewGroup parent) {if (convertView == null) {convertView = LayoutInflater.from(DeviceScanActivity.this).inflate(R.layout.listitem_device, null);viewHolder = new ViewHolder();viewHolder.tv_devName = (TextView) convertView.findViewById(R.id.device_name);viewHolder.tv_devAddress = (TextView) convertView.findViewById(R.id.device_address);convertView.setTag(viewHolder);} else {convertView.getTag();}// add-Parameters//设置蓝牙名称和mac地址如果没有名称就设置为“unknow-device”BluetoothDevice device = mBleArray.get(position);String devName = device.getName();if (devName != null && devName.length() > 0) {viewHolder.tv_devName.setText(devName);} else {viewHolder.tv_devName.setText("unknow-device");}viewHolder.tv_devAddress.setText(device.getAddress());return convertView;}}
//返回蓝牙名字,mac地址class ViewHolder {TextView tv_devName, tv_devAddress;}}

查看SCAN_VIEW.xml的design界面,如果是显示空白的,代表导入ITEM_BLE_LIST.xml没成功,在检查ITEM_BLE_LIST.xml。可能是有引用的资源没有,导致无法显示。下图是正常,没有导入成功就是空白的。

在代码转移的时候遇到过这个问题,没有报错,能够运行,但是不显示。

创建第二个界面

如下图所示

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:layout_height="wrap_content"android:layout_margin="5dp"android:orientation="vertical" ><LinearLayoutandroid:layout_width="match_parent"android:layout_height="wrap_content"android:layout_margin="1dp"android:orientation="horizontal" ><TextViewandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:text="@string/label_device_address"android:textSize="14sp" /><TextViewandroid:id="@+id/device_address"android:layout_width="match_parent"android:layout_height="wrap_content"android:textSize="14sp" /></LinearLayout><LinearLayoutandroid:layout_width="match_parent"android:layout_height="wrap_content"android:layout_margin="1dp"android:orientation="horizontal" ><TextViewandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:text="@string/label_state"android:textSize="14sp" /><TextViewandroid:id="@+id/connection_state"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="@string/disconnected"android:textSize="14sp" /></LinearLayout><LinearLayoutandroid:layout_width="match_parent"android:layout_height="wrap_content"android:layout_margin="1dp"android:layout_marginLeft="10dp"android:layout_marginRight="10dp"android:background="#00f0e0"android:orientation="horizontal" ><TextViewandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:text="@string/label_data"android:textSize="12sp" /><TextViewandroid:id="@+id/data_value"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="@string/no_data"android:textSize="12sp" /><CheckBoxandroid:id="@+id/checkBox5"android:layout_width="wrap_content"android:layout_height="20dp"android:layout_marginLeft="50dp"android:layout_marginTop="0dp"android:text="hex收" /></LinearLayout><LinearLayoutandroid:layout_width="match_parent"android:layout_height="wrap_content"android:orientation="vertical" ><EditTextandroid:id="@+id/rx_data_id_1"android:layout_width="fill_parent"android:layout_height="60dp"android:enabled="true"android:focusable="false"android:gravity="top"android:inputType="textMultiLine"android:maxLines="10"android:minLines="5"android:scrollbars="vertical"android:textSize="10dp" /></LinearLayout><LinearLayoutandroid:layout_width="match_parent"android:layout_height="25dp"android:layout_marginLeft="10dp"android:layout_marginRight="10dp"android:layout_marginTop="0dp"android:background="#00f0e0"android:orientation="horizontal" ><TextViewandroid:id="@+id/tx"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="@string/TXD"android:textSize="12sp" /><CheckBoxandroid:id="@+id/checkBox1"android:layout_width="wrap_content"android:layout_height="20dp"android:layout_marginLeft="25dp"android:text="hex发" /><CheckBoxandroid:id="@+id/checkBox1_tc_send"android:layout_width="wrap_content"android:layout_height="10dp"android:layout_marginLeft="40dp"android:text="连续发"android:visibility="invisible" /></LinearLayout><LinearLayoutandroid:layout_width="match_parent"android:layout_height="wrap_content"android:orientation="horizontal" ><EditTextandroid:id="@+id/tx_text"android:layout_width="match_parent"android:layout_height="wrap_content"android:layout_marginLeft="2dp"android:textSize="11sp" ></EditText></LinearLayout><LinearLayoutandroid:layout_width="match_parent"android:layout_height="wrap_content"android:orientation="horizontal" ><TextViewandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:background="#00f0e0"android:text="以上部份为普通 APP透传功能,一般客户需要使用APP透传数据的话,请使用以上串口中功能"android:textSize="11dp" /></LinearLayout><LinearLayoutandroid:layout_width="match_parent"android:layout_height="wrap_content"android:layout_marginTop="1dp"android:orientation="horizontal" ><Buttonandroid:id="@+id/tx_button"android:layout_width="60dp"android:layout_height="30dp"android:layout_marginLeft="50dp"android:text="发送"android:textSize="10sp" /><Buttonandroid:id="@+id/clear_button"android:layout_width="60dp"android:layout_height="30dp"android:layout_marginLeft="50dp"android:text="清除"android:textSize="10sp" /></LinearLayout><LinearLayoutandroid:layout_width="match_parent"android:layout_height="wrap_content"android:layout_marginLeft="1dp"android:layout_marginRight="1dp"android:layout_marginTop="10dp"android:background="#f00000"android:orientation="horizontal" ><TextViewandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:text="以下为MESH(串口透传、IO、PWM、LED灯、支持一对多,多对一,多对多通信"android:textSize="12sp" /></LinearLayout><LinearLayoutandroid:layout_width="match_parent"android:layout_height="wrap_content"android:layout_marginLeft="1dp"android:layout_marginRight="1dp"android:layout_marginTop="2dp"android:orientation="horizontal" ><EditTextandroid:id="@+id/mesh_tx_text"android:layout_width="200dp"android:layout_height="wrap_content"android:layout_marginLeft="2dp"android:textSize="11sp" ></EditText><TextViewandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:text="注意请输入十六进制数据,mesh串口透传时,最大输入字节为10字节"android:textSize="10sp"android:textColor="#ff0000"/></LinearLayout><LinearLayoutandroid:layout_width="match_parent"android:layout_height="wrap_content"android:layout_marginLeft="1dp"android:layout_marginRight="1dp"android:layout_marginTop="2dp"android:orientation="horizontal" ><Buttonandroid:layout_width="wrap_content"android:layout_height="30dp"android:text="发送Mesh串口数据"android:id="@+id/mesh_usrt_send_button"android:textSize="11dp" /><Buttonandroid:layout_width="wrap_content"android:layout_height="30dp"android:text="发送Mesh控制数据"android:id="@+id/mesh_fc_send_button"android:textSize="11dp" /><TextViewandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:text="IO广播"android:layout_marginLeft="10dp"android:textSize="12sp" /><ToggleButtonandroid:layout_width="50dp"android:layout_height="40dp"android:id="@+id/mesh_io_button"android:text="ToggleButton" /></LinearLayout>
</LinearLayout>

同样右上角需要一个连接/断开的按钮

也是在menu创建一个

<menu xmlns:android="http://schemas.android.com/apk/res/android"><item android:id="@+id/menu_refresh"android:checkable="false"android:orderInCategory="1"android:showAsAction="ifRoom"/><item android:id="@+id/menu_connect"android:title="@string/menu_connect"android:orderInCategory="100"android:showAsAction="ifRoom|withText"/><item android:id="@+id/menu_disconnect"android:title="@string/menu_disconnect"android:orderInCategory="101"android:showAsAction="ifRoom|withText"/>
</menu>

控制端代码(删减了部分):


import androidx.appcompat.app.AppCompatActivity;import android.app.Activity;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattService;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;public class BLE_B extends AppCompatActivity {public static final String EXTRAS_DEVICE_NAME = "DEVICE_NAME";public static final String EXTRAS_DEVICE_ADDRESS = "DEVICE_ADDRESS";private static final String TAG ="LZT" ;private StringBuffer sbValues;private TextView mConnectionState;private TextView mDataField;private String mDeviceName;private String mDeviceAddress;private ExpandableListView mGattServicesList;private BluetoothLeService mBluetoothLeService;private ArrayList<ArrayList<BluetoothGattCharacteristic>> mGattCharacteristics =new ArrayList<ArrayList<BluetoothGattCharacteristic>>();private boolean mConnected = false;private BluetoothGattCharacteristic mNotifyCharacteristic;boolean connect_status_bit=false;private final String LIST_NAME = "NAME";private final String LIST_UUID = "UUID";private Handler mHandler;// Stops scanning after 10 seconds.private static final long SCAN_PERIOD = 1000;private int i = 0;private int TIME = 1000;ToggleButton key1;int tx_count = 0;int connect_count = 0;// Code to manage Service lifecycle.private final ServiceConnection mServiceConnection = new ServiceConnection() {@Overridepublic void onServiceConnected(ComponentName componentName, IBinder service) {mBluetoothLeService = ((BluetoothLeService.LocalBinder) service).getService();if (!mBluetoothLeService.initialize()) {Log.e("BLE2", "Unable to initialize Bluetooth");Toast.makeText(getApplicationContext(),"Unable to initialize Bluetooth",Toast.LENGTH_SHORT).show();finish();}// Automatically connects to the device upon successful start-up initialization.mBluetoothLeService.connect(mDeviceAddress);}@Overridepublic void onServiceDisconnected(ComponentName componentName) {mBluetoothLeService = null;}};// Handles various events fired by the Service.// ACTION_GATT_CONNECTED: connected to a GATT server.// ACTION_GATT_DISCONNECTED: disconnected from a GATT server.// ACTION_GATT_SERVICES_DISCOVERED: discovered GATT services.// ACTION_DATA_AVAILABLE: received data from the device.  This can be a result of read//                        or notification operations.private final BroadcastReceiver mGattUpdateReceiver = new BroadcastReceiver() {@Overridepublic void onReceive(Context context, Intent intent) {final String action = intent.getAction();if (BluetoothLeService.ACTION_GATT_CONNECTED.equals(action)) {//mConnected = true;connect_status_bit=true;invalidateOptionsMenu();} else if (BluetoothLeService.ACTION_GATT_DISCONNECTED.equals(action)) {mConnected = false;updateConnectionState(R.string.disconnected);Toast.makeText(getApplicationContext(),"连接失败/断开",Toast.LENGTH_SHORT).show();connect_status_bit=false;show_view(false);invalidateOptionsMenu();clearUI();if( connect_count==0 ){connect_count =1;Message message = new Message();message.what = 1;handler.sendMessage(message);}} else if (BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED.equals(action)) {// Show all the supported services and characteristics on the user interface.displayGattServices(mBluetoothLeService.getSupportedGattServices());}else if (BluetoothLeService.ACTION_DATA_AVAILABLE.equals(action))//接收FFE1串口透传数据{//displayData(intent.getStringExtra(BluetoothLeService.EXTRA_DATA));//byte data1;//intent.getByteArrayExtra(BluetoothLeService.EXTRA_DATA);//  .getByteExtra(BluetoothLeService.EXTRA_DATA, data1);displayData( intent.getByteArrayExtra(BluetoothLeService.EXTRA_DATA) );}else if (BluetoothLeService.ACTION_DATA_AVAILABLE1.equals(action))//接收FFE2功能配置返回数据{displayData1( intent.getByteArrayExtra(BluetoothLeService.EXTRA_DATA1) );}}};// If a given GATT characteristic is selected, check for supported features.  This sample// demonstrates 'Read' and 'Notify' features.  See// http://d.android.com/reference/android/bluetooth/BluetoothGatt.html for the complete// list of supported characteristic features.private final ExpandableListView.OnChildClickListener servicesListClickListner =new ExpandableListView.OnChildClickListener() {@Overridepublic boolean onChildClick(ExpandableListView parent, View v, int groupPosition,int childPosition, long id) {return false;}};private void clearUI() {//mGattServicesList.setAdapter((SimpleExpandableListAdapter) null);mDataField.setText(R.string.no_data);}Button send_button;EditText txd_txt,rx_data_id_1;Button clear_button;Button mesh_usrt_send_button;Button mesh_fc_send_button;EditText mesh_tx_text;Timer timer = new Timer();//    TextView textView5;CheckBox checkBox5,checkBox1,checkBox1_tc_send;TextView tx;boolean send_hex = true;//HEX格式发送数据 透传boolean rx_hex = false;//HEX格式接收数据 透传Thread thread;boolean lx_send = false;void show_view( boolean p ){if(p){send_button.setEnabled(true);key1.setEnabled(true);}else{send_button.setEnabled(false);key1.setEnabled(false);}}public void delay(int ms){try {Thread.currentThread();Thread.sleep(ms);} catch (InterruptedException e) {e.printStackTrace();}}public static String numToHex8(int b) {return String.format("%02x", b);//2表示需要两个16进制数}@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_ble__b);final Intent intent = getIntent();mDeviceName = intent.getStringExtra(EXTRAS_DEVICE_NAME);mDeviceAddress = intent.getStringExtra(EXTRAS_DEVICE_ADDRESS);setTitle(mDeviceName);mesh_tx_text = (EditText) findViewById(R.id.mesh_tx_text);// Sets up UI references.((TextView) findViewById(R.id.device_address)).setText(mDeviceAddress);mConnectionState = (TextView) findViewById(R.id.connection_state);mDataField = (TextView) findViewById(R.id.data_value);send_button=(Button)findViewById(R.id.tx_button);//send data 1002send_button.setOnClickListener(listener);//设置监听mesh_usrt_send_button=(Button)findViewById(R.id.mesh_usrt_send_button);//发送MESH串口数据mesh_fc_send_button=(Button)findViewById(R.id.mesh_fc_send_button);//发送MESH控制数据mesh_usrt_send_button.setOnClickListener(listener);mesh_fc_send_button.setOnClickListener(listener);clear_button=(Button)findViewById(R.id.clear_button);//send data 1002clear_button.setOnClickListener(listener);txd_txt=(EditText)findViewById(R.id.tx_text);//1002 datatxd_txt.setText("");txd_txt.clearFocus();rx_data_id_1=(EditText)findViewById(R.id.rx_data_id_1);//1002 datarx_data_id_1.setText("");key1 = (ToggleButton)findViewById(R.id.mesh_io_button);key1.setOnClickListener( OnClickListener_listener );tx = (TextView)findViewById(R.id.tx);sbValues = new StringBuffer();mHandler = new Handler();checkBox5 = (CheckBox)findViewById(R.id.checkBox5);checkBox1 = (CheckBox)findViewById(R.id.checkBox1);checkBox5.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener(){@Overridepublic void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {// TODO Auto-generated method stubif(isChecked){rx_hex = true;}else{rx_hex = false;}}});checkBox1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener(){@Overridepublic void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {// TODO Auto-generated method stubif(isChecked){send_hex = false;}else{send_hex = true;}}});checkBox1_tc_send = (CheckBox)findViewById(R.id.checkBox1_tc_send);checkBox1_tc_send.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener(){@Overridepublic void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {// TODO Auto-generated method stubif(isChecked){lx_send = true;}else{lx_send = false;}}});Message message = new Message();message.what = 1;handler.sendMessage(message);registerReceiver(mGattUpdateReceiver, makeGattUpdateIntentFilter());if (mBluetoothLeService != null) {final boolean result = mBluetoothLeService.connect(mDeviceAddress);Log.d("BLE2", "Connect request result=" + result);}boolean sg;Intent gattServiceIntent = new Intent(this, BluetoothLeService.class);sg = bindService(gattServiceIntent, mServiceConnection, BIND_AUTO_CREATE);updateConnectionState(R.string.connecting);show_view(false);get_pass();thread=new Thread(new Runnable(){@Overridepublic void run(){while( true ){if( lx_send&&mConnected ){String tx_string=txd_txt.getText().toString().trim();tx_count+=mBluetoothLeService.txxx( tx_string,send_hex );//发送数据串字符Message message=new Message();message.what=1010;message.arg1 = tx_count;handler.sendMessage(message);}}}});thread.start();}public void enable_pass(){mBluetoothLeService.Delay_ms( 100 );mBluetoothLeService.set_APP_PASSWORD( password_value );}String password_value = "123456";public void get_pass(){password_value = getSharedPreference( "DEV_PASSWORD_LEY_1000" );if( password_value!=null||password_value!=""){if( password_value.length()==6 ){}else password_value = "123456" ;}else password_value = "123456" ;}//---------------------------------------------------------------------------------// 应用于存储选择TAB的列表indexpublic String getSharedPreference(String key){//在读取SharePreferences数据钱要实例化一个对象SharedPreferences sharedPreferences= getSharedPreferences("test",Activity.MODE_PRIVATE);// 使用getString方法获取value,第二个参数是value的默认值String name =sharedPreferences.getString(key, "");return name;}public void setSharedPreference(String key, String values){//实例化对象SharedPreferences mySharedPreferences= getSharedPreferences("test",Activity.MODE_PRIVATE);//实例化SharedPreferences.Editor对象SharedPreferences.Editor editor = mySharedPreferences.edit();//用putString方法保存数据editor.putString(key, values );//提交editor.commit();//Toast.makeText(this, values ,//Toast.LENGTH_LONG).show();}Handler handler = new Handler() {public void handleMessage(Message msg) {if (msg.what == 1010){//String tx_string=txd_txt.getText().toString().trim();//tx_count+=mBluetoothLeService.txxx( tx_string,send_hex );tx.setText("发送数据:"+msg.arg1);}if (msg.what == 1){//tvShow.setText(Integer.toString(i++));//scanLeDevice(true);if (mBluetoothLeService != null) {if( mConnected==false ){updateConnectionState(R.string.connecting);final boolean result = mBluetoothLeService.connect(mDeviceAddress);Log.d("BLE2", "Connect request result=" + result);}}}if (msg.what == 2){try {Thread.currentThread();Thread.sleep(100);} catch (InterruptedException e) {e.printStackTrace();}mBluetoothLeService.enable_JDY_ble( 0 );try {Thread.currentThread();Thread.sleep(100);} catch (InterruptedException e) {e.printStackTrace();}mBluetoothLeService.enable_JDY_ble( 0 );try {Thread.currentThread();Thread.sleep(100);} catch (InterruptedException e) {e.printStackTrace();}mBluetoothLeService.enable_JDY_ble( 1 );try {Thread.currentThread();Thread.sleep(100);} catch (InterruptedException e) {e.printStackTrace();}byte[] WriteBytes = new byte[2];WriteBytes[0] = (byte) 0xE7;WriteBytes[1] = (byte) 0xf6;mBluetoothLeService.function_data( WriteBytes );// 发送读取所有IO状态}super.handleMessage(msg);};};TimerTask task = new TimerTask() {@Overridepublic void run() {// 发送数据Message message = new Message();message.what = 1;handler.sendMessage(message);}};ToggleButton.OnClickListener OnClickListener_listener = new ToggleButton.OnClickListener(){@Overridepublic void onClick(View v){if( mConnected ){boolean on = ((ToggleButton) v).isChecked();if (on){//FF表示广播通信方式,这个FF改成设备的短地址,可以指定设备控制mBluetoothLeService.function_fc( "E7FFFF","ff" );}else{//FF表示广播通信方式,这个FF改成设备的短地址,可以指定设备控制mBluetoothLeService.function_fc( "E7F000","ff" );//}//}}}};Button.OnClickListener listener = new Button.OnClickListener(){public void onClick(View v){switch( v.getId()){case R.id.tx_button ://uuid1002 数据通道发送数据if( connect_status_bit ){if( mConnected ){String tx_string=txd_txt.getText().toString().trim();tx_count+=mBluetoothLeService.txxx( tx_string,send_hex );//发送字符串信息tx.setText("发送数据:"+tx_count);//mBluetoothLeService.txxx( tx_string,false );// 发送HEX数据}}else{Toast toast = Toast.makeText(BLE_B.this, "设备没有连接!", Toast.LENGTH_SHORT);toast.show();}break;case R.id.clear_button:{sbValues.delete(0,sbValues.length());len_g =0;da = "";rx_data_id_1.setText( da );mDataField.setText( ""+len_g );tx_count = 0;tx.setText("发送数据:"+tx_count);}break;case R.id.mesh_usrt_send_button:{if( mConnected )//mesh_send{String tx_string=mesh_tx_text.getText().toString().trim();
//FF表示广播通信,FF改成设备的短地址实现指定设备的控制if(mBluetoothLeService.function_data( tx_string,"ff" )==0 );else Toast.makeText(BLE_B.this, "发送失败", Toast.LENGTH_SHORT).show();}}break;case R.id.mesh_fc_send_button:{if( mConnected ){String tx_string=mesh_tx_text.getText().toString().trim();
//FF表示广播通信,FF改成设备的短地址实现指定设备的控制if(mBluetoothLeService.function_fc( tx_string,"ff" )==0 );//ff表示广播所有设备都可以同时收到串口数据else Toast.makeText(BLE_B.this, "发送失败", Toast.LENGTH_SHORT).show();}}break;default :break;}}};@Overrideprotected void onResume() {super.onResume();}@Overrideprotected void onPause() {super.onPause();}@Overridepublic boolean onOptionsItemSelected(MenuItem item) {switch(item.getItemId()) {case android.R.id.home:onBackPressed();return true;}return super.onOptionsItemSelected(item);}private void updateConnectionState(final int resourceId) {runOnUiThread(new Runnable() {@Overridepublic void run() {mConnectionState.setText(resourceId);}});}String da="";int len_g = 0;private void displayData( byte[] data1 )//接收FFE1串口透传通道数据{//String head1,data_0;/*head1=data1.substring(0,2);data_0=data1.substring(2);*///da = da+data1+"\n";if (data1 != null && data1.length > 0){//rx_data_id_1.setText( mBluetoothLeService.bytesToHexString(data1) );//if( rx_hex ){final StringBuilder stringBuilder = new StringBuilder( sbValues.length()  );byte[] WriteBytes = mBluetoothLeService.hex2byte( stringBuilder.toString().getBytes() );for(byte byteChar : data1)stringBuilder.append(String.format(" %02X", byteChar));String da = stringBuilder.toString();//sbValues.append( stringBuilder.toString() ) ;//rx_data_id_1.setText( mBluetoothLeService.String_to_HexString(sbValues.toString()) );//String res = new String( da.getBytes()  );sbValues.append( da );rx_data_id_1.setText( sbValues.toString() );}else{String res = new String( data1 );sbValues.append( res ) ;rx_data_id_1.setText( sbValues.toString() );}len_g += data1.length;//          // data1 );if( sbValues.length()<=rx_data_id_1.getText().length() )rx_data_id_1.setSelection( sbValues.length() );if( sbValues.length()>=5000 )sbValues.delete(0,sbValues.length());mDataField.setText( ""+len_g );//rx_data_id_1.setGravity(Gravity.BOTTOM);//rx_data_id_1.setSelection(rx_data_id_1.getText().length());}}private void displayData1( byte[] data1 )//接收FFE2功能配置返回的数据{//String str = mBluetoothLeService.bytesToHexString1( data1 );// 将接收的16进制数据转换成16进制字符串if( data1.length==5&&data1[0]==(byte) 0xf6 )//判断是否读取IO状态位{}else if( data1.length==2&&data1[0]==(byte) 0x55 )//判断APP连接密码是否正确{if( data1[1]==(byte) 0x01 ){
//              Toast.makeText(jdy_Activity.this, "提示!APP密码连接成功", Toast.LENGTH_SHORT).show();}else{}}}// Demonstrates how to iterate through the supported GATT Services/Characteristics.// In this sample, we populate the data structure that is bound to the ExpandableListView// on the UI.private void displayGattServices(List<BluetoothGattService> gattServices) {if (gattServices == null) return;mBluetoothLeService.Delay_ms( 300 );if( gattServices.size()>0&&mBluetoothLeService.get_connected_status( gattServices )==1 )//表示JDY-06、JDY-08系列{connect_count = 0;if( connect_status_bit ){mConnected = true;show_view( true );updateConnectionState(R.string.connected);//enable_pass();}}else if( gattServices.size()>0/*&&mBluetoothLeService.get_connected_status( gattServices )==1*/ )// 表示JDY-09、JDY-10系列{connect_count = 0;if( connect_status_bit ){mConnected = true;show_view( true );mBluetoothLeService.Delay_ms( 100 );mBluetoothLeService.enable_JDY_ble( 0 );mBluetoothLeService.Delay_ms( 100 );mBluetoothLeService.enable_JDY_ble( 1 );updateConnectionState(R.string.connected);//enable_pass();}{Toast toast = Toast.makeText(BLE_B.this, "已经连接上"+mDeviceName, Toast.LENGTH_SHORT);toast.show();}}}private static 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(BluetoothLeService.ACTION_DATA_AVAILABLE1);return intentFilter;}@Overrideprotected void onDestroy() {super.onDestroy();unbindService(mServiceConnection);Log.d(TAG, "onDestroy: 走了");mBluetoothLeService.disconnect();mBluetoothLeService = null;timer.cancel();timer=null;}}
SampleGattAttributes.class

这个是UUID。


import java.util.HashMap;/*** This class includes a small subset of standard GATT attributes for demonstration purposes.*/
public class SampleGattAttributes {private static HashMap<String, String> attributes = new HashMap();public static String HEART_RATE_MEASUREMENT = "00002a37-0000-1000-8000-00805f9b34fb";public static String CLIENT_CHARACTERISTIC_CONFIG = "00002902-0000-1000-8000-00805f9b34fb";public static String Service_uuid11 = "0000ffe0-0000-1000-8000-00805f9b34fb";public static String Characteristic_uuid_TX11 = "0000ffe1-0000-1000-8000-00805f9b34fb";public static String Characteristic_uuid_RX11 = "0000ffe1-0000-1000-8000-00805f9b34fb";static {// Sample Services.attributes.put("0000180d-0000-1000-8000-00805f9b34fb", "Heart Rate Service");attributes.put("0000180a-0000-1000-8000-00805f9b34fb", "Device Information Service");// Sample Characteristics.attributes.put(HEART_RATE_MEASUREMENT, "Heart Rate Measurement");attributes.put("00002a29-0000-1000-8000-00805f9b34fb", "Manufacturer Name String");}public static String lookup(String uuid, String defaultName) {String name = attributes.get(uuid);return name == null ? defaultName : name;}
}

以及给的一个包,自己改了一下,原来那个因为是jar,无法修改,转到自己的代码里有些地方无法运行,因此拿出来了,直接复制有一堆错误就改了。这个直接复制就好,我也懒得看了……


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.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;public class BluetoothLeService extends Service {private static final String TAG = BluetoothLeService.class.getSimpleName();private BluetoothManager mBluetoothManager;private BluetoothAdapter mBluetoothAdapter;private String mBluetoothDeviceAddress;private BluetoothGatt mBluetoothGatt;private int mConnectionState = 0;private static final int STATE_DISCONNECTED = 0;private static final int STATE_CONNECTING = 1;private static final int STATE_CONNECTED = 2;public static final String ACTION_GATT_CONNECTED = "com.example.bluetooth.le.ACTION_GATT_CONNECTED";public static final String ACTION_GATT_DISCONNECTED = "com.example.bluetooth.le.ACTION_GATT_DISCONNECTED";public static final String ACTION_GATT_SERVICES_DISCOVERED = "com.example.bluetooth.le.ACTION_GATT_SERVICES_DISCOVERED";public static final String ACTION_DATA_AVAILABLE = "com.example.bluetooth.le.ACTION_DATA_AVAILABLE";public static final String ACTION_DATA_AVAILABLE1 = "com.example.bluetooth.le.ACTION_DATA_AVAILABLE1";public static final String EXTRA_DATA = "com.example.bluetooth.le.EXTRA_DATA";public static final String EXTRA_DATA1 = "com.example.bluetooth.le.EXTRA_DATA1";public static final String EXTRA_UUID = "com.example.bluetooth.le.uuid_DATA";public static final String EXTRA_NAME = "com.example.bluetooth.le.name_DATA";public static final String EXTRA_PASSWORD = "com.example.bluetooth.le.password_DATA";private ArrayList<ArrayList<BluetoothGattCharacteristic>> mGattCharacteristics = new ArrayList();public static final UUID UUID_HEART_RATE_MEASUREMENT;public static String Service_uuid;public static String Characteristic_uuid_TX;public static String Characteristic_uuid_FUNCTION;byte tx_cnt = 1;byte[] WriteBytes = new byte[200];private final BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {String intentAction;if (newState == 2) {intentAction = "com.example.bluetooth.le.ACTION_GATT_CONNECTED";BluetoothLeService.this.mConnectionState = 2;BluetoothLeService.this.broadcastUpdate(intentAction);Log.i(BluetoothLeService.TAG, "Connected to GATT server.");Log.i(BluetoothLeService.TAG, "Attempting to start service discovery:" + BluetoothLeService.this.mBluetoothGatt.discoverServices());} else if (newState == 0) {intentAction = "com.example.bluetooth.le.ACTION_GATT_DISCONNECTED";BluetoothLeService.this.mConnectionState = 0;Log.i(BluetoothLeService.TAG, "Disconnected from GATT server.");BluetoothLeService.this.broadcastUpdate(intentAction);}}public void onServicesDiscovered(BluetoothGatt gatt, int status) {if (status == 0) {BluetoothLeService.this.broadcastUpdate("com.example.bluetooth.le.ACTION_GATT_SERVICES_DISCOVERED");} else {Log.w(BluetoothLeService.TAG, "onServicesDiscovered received: " + status);}}public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {if (status == 0) {if (UUID.fromString(BluetoothLeService.Characteristic_uuid_TX).equals(characteristic.getUuid())) {BluetoothLeService.this.broadcastUpdate("com.example.bluetooth.le.ACTION_DATA_AVAILABLE", characteristic);} else if (UUID.fromString(BluetoothLeService.Characteristic_uuid_FUNCTION).equals(characteristic.getUuid())) {BluetoothLeService.this.broadcastUpdate("com.example.bluetooth.le.ACTION_DATA_AVAILABLE1", characteristic);}}}public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {if (UUID.fromString(BluetoothLeService.Characteristic_uuid_TX).equals(characteristic.getUuid())) {BluetoothLeService.this.broadcastUpdate("com.example.bluetooth.le.ACTION_DATA_AVAILABLE", characteristic);} else if (UUID.fromString(BluetoothLeService.Characteristic_uuid_FUNCTION).equals(characteristic.getUuid())) {BluetoothLeService.this.broadcastUpdate("com.example.bluetooth.le.ACTION_DATA_AVAILABLE1", characteristic);}}};private final IBinder mBinder = new BluetoothLeService.LocalBinder();static {UUID_HEART_RATE_MEASUREMENT = UUID.fromString(SampleGattAttributes.HEART_RATE_MEASUREMENT);Service_uuid = "0000ffe0-0000-1000-8000-00805f9b34fb";Characteristic_uuid_TX = "0000ffe1-0000-1000-8000-00805f9b34fb";Characteristic_uuid_FUNCTION = "0000ffe2-0000-1000-8000-00805f9b34fb";}public BluetoothLeService() {}public String bin2hex(String bin) {char[] digital = "0123456789ABCDEF".toCharArray();StringBuffer sb = new StringBuffer("");byte[] bs = bin.getBytes();for(int i = 0; i < bs.length; ++i) {int bit = (bs[i] & 240) >> 4;sb.append(digital[bit]);bit = bs[i] & 15;sb.append(digital[bit]);}return sb.toString();}public byte[] hex2byte(byte[] b) {if (b.length % 2 != 0) {throw new IllegalArgumentException("长度不是偶数");} else {byte[] b2 = new byte[b.length / 2];for(int n = 0; n < b.length; n += 2) {String item = new String(b, n, 2);b2[n / 2] = (byte)Integer.parseInt(item, 16);}b = null;return b2;}}void deley(int ms) {try {Thread.currentThread();Thread.sleep((long)ms);} catch (InterruptedException var3) {var3.printStackTrace();}}public String getStringByBytes(byte[] bytes) {String result = null;String hex = null;if (bytes != null && bytes.length > 0) {StringBuilder stringBuilder = new StringBuilder(bytes.length);byte[] var8 = bytes;int var7 = bytes.length;for(int var6 = 0; var6 < var7; ++var6) {byte byteChar = var8[var6];hex = Integer.toHexString(byteChar & 255);if (hex.length() == 1) {hex = '0' + hex;}stringBuilder.append(hex.toUpperCase());}result = stringBuilder.toString();}return result;}private static byte charToByte(char c) {return (byte)"0123456789ABCDEF".indexOf(c);}public static byte[] getBytesByString(String data) {byte[] bytes = null;if (data != null) {data = data.toUpperCase();int length = data.length() / 2;char[] dataChars = data.toCharArray();bytes = new byte[length];for(int i = 0; i < length; ++i) {int pos = i * 2;bytes[i] = (byte)(charToByte(dataChars[pos]) << 4 | charToByte(dataChars[pos + 1]));}}return bytes;}public String bytesToHexString(byte[] src) {StringBuilder stringBuilder = new StringBuilder(src.length);byte[] var6 = src;int var5 = src.length;for(int var4 = 0; var4 < var5; ++var4) {byte byteChar = var6[var4];stringBuilder.append(String.format("%02X", byteChar));}return stringBuilder.toString();}public String bytesToHexString1(byte[] src) {StringBuilder stringBuilder = new StringBuilder(src.length);byte[] var6 = src;int var5 = src.length;for(int var4 = 0; var4 < var5; ++var4) {byte byteChar = var6[var4];stringBuilder.append(String.format(" %02X", byteChar));}return stringBuilder.toString();}public String bytesToHexString1(byte[] src, int index) {if (src == null) {return null;} else {StringBuilder stringBuilder = new StringBuilder(src.length);for(int i = index; i < src.length; ++i) {stringBuilder.append(String.format(" %02X", src[i]));}return stringBuilder.toString();}}public String String_to_HexString0(String str) {String st = str.toString();byte[] WriteBytes = new byte[st.length()];WriteBytes = st.getBytes();return this.bytesToHexString(WriteBytes);}public String String_to_HexString(String str) {String st = str.toString();byte[] WriteBytes = new byte[st.length()];WriteBytes = st.getBytes();return this.bytesToHexString1(WriteBytes);}public byte[] String_to_byte(String str) {String st = str.toString();byte[] WriteBytes = new byte[st.length()];return WriteBytes;}public String byte_to_String(byte[] byt) {String t = new String(byt);return t;}public String byte_to_String(byte[] byt, int index) {if (byt == null) {return null;} else {byte[] WriteBytes = new byte[byt.length - index];for(int i = index; i < byt.length; ++i) {WriteBytes[i - index] = byt[i];}String t = new String(WriteBytes);return t;}}public int txxx(String g, boolean string_or_hex_data) {int ic = 0;if (string_or_hex_data) {this.WriteBytes = g.getBytes();} else {this.WriteBytes = getBytesByString(g);}int length = this.WriteBytes.length;int data_len_20 = length / 20;int data_len_0 = length % 20;int i = 0;byte[] da;int h;BluetoothGattCharacteristic gg;if (data_len_20 > 0) {while(i < data_len_20) {da = new byte[20];for(h = 0; h < 20; ++h) {da[h] = this.WriteBytes[20 * i + h];}gg = this.mBluetoothGatt.getService(UUID.fromString(Service_uuid)).getCharacteristic(UUID.fromString(Characteristic_uuid_TX));gg.setValue(da);this.mBluetoothGatt.writeCharacteristic(gg);this.deley(23);ic += 20;++i;}}if (data_len_0 > 0) {da = new byte[data_len_0];for(h = 0; h < data_len_0; ++h) {da[h] = this.WriteBytes[20 * i + h];}gg = this.mBluetoothGatt.getService(UUID.fromString(Service_uuid)).getCharacteristic(UUID.fromString(Characteristic_uuid_TX));gg.setValue(da);this.mBluetoothGatt.writeCharacteristic(gg);ic += data_len_0;this.deley(23);}return ic;}public void function_data(byte[] data) {this.WriteBytes = data;BluetoothGattCharacteristic gg = this.mBluetoothGatt.getService(UUID.fromString(Service_uuid)).getCharacteristic(UUID.fromString(Characteristic_uuid_FUNCTION));gg.setValue(this.WriteBytes);this.mBluetoothGatt.writeCharacteristic(gg);}public int function_data(String data, String Target_address) {boolean p = false;if (data == null) {return 1;} else if (data.length() > 20) {return 2;} else if (Target_address != "" && Target_address != null) {if (Target_address.length() != 2) {return 4;} else {String txt = "FAff";String value = this.bin2hex(data);txt = txt + value;this.WriteBytes = this.hex2byte(txt.toString().getBytes());BluetoothGattCharacteristic gg = this.mBluetoothGatt.getService(UUID.fromString(Service_uuid)).getCharacteristic(UUID.fromString(Characteristic_uuid_FUNCTION));gg.setValue(this.WriteBytes);this.mBluetoothGatt.writeCharacteristic(gg);return 0;}} else {return 3;}}public int function_fc(String data, String Target_address) {boolean p = false;if (data == null) {return 1;} else if (data.length() > 20) {return 2;} else if (Target_address != "" && Target_address != null) {if (Target_address.length() != 2) {return 4;} else {String txt = "FB" + Target_address;txt = txt + data;this.WriteBytes = this.hex2byte(txt.toString().getBytes());BluetoothGattCharacteristic gg = this.mBluetoothGatt.getService(UUID.fromString(Service_uuid)).getCharacteristic(UUID.fromString(Characteristic_uuid_FUNCTION));gg.setValue(this.WriteBytes);this.mBluetoothGatt.writeCharacteristic(gg);return 0;}} else {return 3;}}public void enable_JDY_ble(int p) {try {BluetoothGattService service = this.mBluetoothGatt.getService(UUID.fromString(Service_uuid));BluetoothGattCharacteristic ale;switch(p) {case 0:ale = service.getCharacteristic(UUID.fromString(Characteristic_uuid_TX));break;case 1:ale = service.getCharacteristic(UUID.fromString(Characteristic_uuid_FUNCTION));break;default:ale = service.getCharacteristic(UUID.fromString(Characteristic_uuid_TX));}this.mBluetoothGatt.setCharacteristicNotification(ale, true);BluetoothGattDescriptor dsc = ale.getDescriptor(UUID.fromString("00002902-0000-1000-8000-00805f9b34fb"));byte[] bytes = new byte[]{1, 0};dsc.setValue(bytes);this.mBluetoothGatt.writeDescriptor(dsc);} catch (NumberFormatException var8) {var8.printStackTrace();}}public String get_mem_data(String key) {SharedPreferences sharedPreferences = this.getSharedPreferences("jdy-ble", 0);String name = sharedPreferences.getString(key, "");return name != null && name != "" ? name : "123456";}public void set_mem_data(String key, String values) {SharedPreferences mySharedPreferences = this.getSharedPreferences("jdy-ble", 0);Editor editor = mySharedPreferences.edit();editor.putString(key, values);editor.commit();}public boolean get_password(String password) {boolean p = true;if (password == null) {return false;} else if (password.length() != 6) {return false;} else {String txt = "E552";String value = this.bin2hex(password);txt = txt + value;this.WriteBytes = this.hex2byte(txt.toString().getBytes());BluetoothGattCharacteristic gg = this.mBluetoothGatt.getService(UUID.fromString(Service_uuid)).getCharacteristic(UUID.fromString(Characteristic_uuid_FUNCTION));gg.setValue(this.WriteBytes);this.mBluetoothGatt.writeCharacteristic(gg);return p;}}public boolean set_password(String password, String new_password) {boolean p = true;if (password != null && new_password != null) {String txt = "E551";String value = this.String_to_HexString0(password);txt = txt + value;value = this.String_to_HexString0(new_password);txt = txt + value;this.WriteBytes = this.hex2byte(txt.toString().getBytes());BluetoothGattCharacteristic gg = this.mBluetoothGatt.getService(UUID.fromString(Service_uuid)).getCharacteristic(UUID.fromString(Characteristic_uuid_FUNCTION));gg.setValue(this.WriteBytes);this.mBluetoothGatt.writeCharacteristic(gg);return p;} else {return false;}}String getutf8FromString(String str) {StringBuffer utfcode = new StringBuffer();try {byte[] var6;int var5 = (var6 = str.getBytes("utf-8")).length;for(int var4 = 0; var4 < var5; ++var4) {byte bit = var6[var4];char hex = (char)(bit & 255);utfcode.append(Integer.toHexString(hex));}} catch (UnsupportedEncodingException var8) {var8.printStackTrace();}return utfcode.toString();}public boolean set_name(String name) {boolean p = true;if (name == null) {return false;} else {String txt = "E661";String value = this.bin2hex(name);txt = txt + value;this.WriteBytes = this.hex2byte(txt.toString().getBytes());BluetoothGattCharacteristic gg = this.mBluetoothGatt.getService(UUID.fromString(Service_uuid)).getCharacteristic(UUID.fromString(Characteristic_uuid_FUNCTION));gg.setValue(this.WriteBytes);this.mBluetoothGatt.writeCharacteristic(gg);return p;}}public boolean MC_Set_angle(String angle) {int length = angle.length();if (angle == null) {return false;} else if (length == 0) {return false;} else {int angle_int_value = Integer.valueOf(angle);boolean m2 = true;boolean p11 = true;String txt = "E7f3";if (angle_int_value <= 9) {txt = txt + "0" + angle_int_value;this.WriteBytes = this.hex2byte(txt.toString().getBytes());BluetoothGattCharacteristic gg = this.mBluetoothGatt.getService(UUID.fromString(Service_uuid)).getCharacteristic(UUID.fromString(Characteristic_uuid_FUNCTION));gg.setValue(this.WriteBytes);this.mBluetoothGatt.writeCharacteristic(gg);}return p11;}}public boolean MC_set_button(boolean p) {boolean m2 = true;boolean p11 = true;String txt = "E7f1";if (p) {txt = "E7f1";txt = txt + "01";} else {txt = "E7f2";txt = txt + "01";}this.WriteBytes = this.hex2byte(txt.toString().getBytes());BluetoothGattCharacteristic gg = this.mBluetoothGatt.getService(UUID.fromString(Service_uuid)).getCharacteristic(UUID.fromString(Characteristic_uuid_FUNCTION));gg.setValue(this.WriteBytes);this.mBluetoothGatt.writeCharacteristic(gg);return p11;}public boolean MC_set_password(String password, String new_password) {boolean p = true;if (password != null && new_password != null) {String txt = "E551";String value = this.String_to_HexString0(password);txt = txt + value;value = this.String_to_HexString0(new_password);txt = txt + value;this.WriteBytes = this.hex2byte(txt.toString().getBytes());BluetoothGattCharacteristic gg = this.mBluetoothGatt.getService(UUID.fromString(Service_uuid)).getCharacteristic(UUID.fromString(Characteristic_uuid_FUNCTION));gg.setValue(this.WriteBytes);this.mBluetoothGatt.writeCharacteristic(gg);return p;} else {return false;}}public boolean set_IO1(boolean p) {boolean p11 = true;String txt = "E7f1";if (p) {txt = txt + "01";} else {txt = txt + "00";}this.WriteBytes = this.hex2byte(txt.toString().getBytes());BluetoothGattCharacteristic gg = this.mBluetoothGatt.getService(UUID.fromString(Service_uuid)).getCharacteristic(UUID.fromString(Characteristic_uuid_FUNCTION));gg.setValue(this.WriteBytes);this.mBluetoothGatt.writeCharacteristic(gg);return p11;}public boolean set_IO2(boolean p) {boolean p11 = true;String txt = "E7f2";if (p) {txt = txt + "01";} else {txt = txt + "00";}this.WriteBytes = this.hex2byte(txt.toString().getBytes());BluetoothGattCharacteristic gg = this.mBluetoothGatt.getService(UUID.fromString(Service_uuid)).getCharacteristic(UUID.fromString(Characteristic_uuid_FUNCTION));gg.setValue(this.WriteBytes);this.mBluetoothGatt.writeCharacteristic(gg);return p11;}public boolean set_IO3(boolean p) {boolean p11 = true;String txt = "E7f3";if (p) {txt = txt + "01";} else {txt = txt + "00";}this.WriteBytes = this.hex2byte(txt.toString().getBytes());BluetoothGattCharacteristic gg = this.mBluetoothGatt.getService(UUID.fromString(Service_uuid)).getCharacteristic(UUID.fromString(Characteristic_uuid_FUNCTION));gg.setValue(this.WriteBytes);this.mBluetoothGatt.writeCharacteristic(gg);return p11;}public boolean set_IO4(boolean p) {boolean p11 = true;String txt = "E7f4";if (p) {txt = txt + "01";} else {txt = txt + "00";}this.WriteBytes = this.hex2byte(txt.toString().getBytes());BluetoothGattCharacteristic gg = this.mBluetoothGatt.getService(UUID.fromString(Service_uuid)).getCharacteristic(UUID.fromString(Characteristic_uuid_FUNCTION));gg.setValue(this.WriteBytes);this.mBluetoothGatt.writeCharacteristic(gg);return p11;}public boolean set_IO_ALL(boolean p) {boolean p11 = true;String txt;if (p) {txt = "E7f5";} else {txt = "E7f0";}this.WriteBytes = this.hex2byte(txt.toString().getBytes());BluetoothGattCharacteristic gg = this.mBluetoothGatt.getService(UUID.fromString(Service_uuid)).getCharacteristic(UUID.fromString(Characteristic_uuid_FUNCTION));gg.setValue(this.WriteBytes);this.mBluetoothGatt.writeCharacteristic(gg);return p11;}public void get_IO_ALL() {String txt = "E7f6";this.WriteBytes = this.hex2byte(txt.toString().getBytes());BluetoothGattCharacteristic gg = this.mBluetoothGatt.getService(UUID.fromString(Service_uuid)).getCharacteristic(UUID.fromString(Characteristic_uuid_FUNCTION));gg.setValue(this.WriteBytes);this.mBluetoothGatt.writeCharacteristic(gg);}public void set_APP_PASSWORD(String pss) {boolean p11 = true;String txt = "E555";String value = this.bin2hex(pss);txt = txt + value;this.WriteBytes = this.hex2byte(txt.toString().getBytes());BluetoothGattCharacteristic gg = this.mBluetoothGatt.getService(UUID.fromString(Service_uuid)).getCharacteristic(UUID.fromString(Characteristic_uuid_FUNCTION));gg.setValue(this.WriteBytes);this.mBluetoothGatt.writeCharacteristic(gg);}public boolean set_ibeacon_UUID(String uuid) {if (uuid.length() == 36) {String v1 = "";String v2 = "";String v3 = "";String v4 = "";v1 = uuid.substring(8, 9);v2 = uuid.substring(13, 14);v3 = uuid.substring(18, 19);v4 = uuid.substring(23, 24);if (v1.equals("-") && v2.equals("-") && v3.equals("-") && v4.equals("-")) {uuid = uuid.replace("-", "");uuid = "E111" + uuid;this.WriteBytes = this.hex2byte(uuid.toString().getBytes());BluetoothGattCharacteristic gg = this.mBluetoothGatt.getService(UUID.fromString(Service_uuid)).getCharacteristic(UUID.fromString(Characteristic_uuid_FUNCTION));gg.setValue(this.WriteBytes);this.mBluetoothGatt.writeCharacteristic(gg);return true;} else {return false;}} else {return false;}}public boolean set_ibeacon_MAJOR(String major) {if (major == null) {return false;} else if (major.length() == 0) {return false;} else {int i = Integer.valueOf(major);String vs = String.format("%02x", i);if (vs.length() == 2) {vs = "00" + vs;} else if (vs.length() == 3) {vs = "0" + vs;}String txt = "E221";txt = txt + vs;this.WriteBytes = this.hex2byte(txt.toString().getBytes());BluetoothGattCharacteristic gg = this.mBluetoothGatt.getService(UUID.fromString(Service_uuid)).getCharacteristic(UUID.fromString(Characteristic_uuid_FUNCTION));gg.setValue(this.WriteBytes);this.mBluetoothGatt.writeCharacteristic(gg);return true;}}public boolean set_ibeacon_MIMOR(String minor) {if (minor == null) {return false;} else if (minor.length() == 0) {return false;} else {int i = Integer.valueOf(minor);String vs = String.format("%02x", i);if (vs.length() == 2) {vs = "00" + vs;} else if (vs.length() == 3) {vs = "0" + vs;}String txt = "E331";txt = txt + vs;this.WriteBytes = this.hex2byte(txt.toString().getBytes());BluetoothGattCharacteristic gg = this.mBluetoothGatt.getService(UUID.fromString(Service_uuid)).getCharacteristic(UUID.fromString(Characteristic_uuid_FUNCTION));gg.setValue(this.WriteBytes);this.mBluetoothGatt.writeCharacteristic(gg);return true;}}public void set_BroadInterval(int interval) {String txt = "E441";String vs = String.format("%02x", interval);txt = txt + vs;this.WriteBytes = this.hex2byte(txt.toString().getBytes());BluetoothGattCharacteristic gg = this.mBluetoothGatt.getService(UUID.fromString(Service_uuid)).getCharacteristic(UUID.fromString(Characteristic_uuid_FUNCTION));gg.setValue(this.WriteBytes);this.mBluetoothGatt.writeCharacteristic(gg);}public void get_BroadInterval() {String txt = "E442";this.WriteBytes = this.hex2byte(txt.toString().getBytes());BluetoothGattCharacteristic gg = this.mBluetoothGatt.getService(UUID.fromString(Service_uuid)).getCharacteristic(UUID.fromString(Characteristic_uuid_FUNCTION));gg.setValue(this.WriteBytes);this.mBluetoothGatt.writeCharacteristic(gg);}public void set_PWM_OPEN(int pwm) {String txt = "E8a1";String vs = String.format("%02x", pwm);txt = txt + vs;this.WriteBytes = this.hex2byte(txt.toString().getBytes());BluetoothGattCharacteristic gg = this.mBluetoothGatt.getService(UUID.fromString(Service_uuid)).getCharacteristic(UUID.fromString(Characteristic_uuid_FUNCTION));gg.setValue(this.WriteBytes);this.mBluetoothGatt.writeCharacteristic(gg);}public void set_PWM_frequency(int frequency) {String txt = "E8a2";String vs = String.format("%02x", frequency);if (vs.length() == 2) {vs = "00" + vs;} else if (vs.length() == 3) {vs = "0" + vs;}txt = txt + vs;this.WriteBytes = this.hex2byte(txt.toString().getBytes());BluetoothGattCharacteristic gg = this.mBluetoothGatt.getService(UUID.fromString(Service_uuid)).getCharacteristic(UUID.fromString(Characteristic_uuid_FUNCTION));gg.setValue(this.WriteBytes);this.mBluetoothGatt.writeCharacteristic(gg);}public void set_PWM1_pulse(int pulse) {String txt = "E8a3";String vs = String.format("%02x", pulse);txt = txt + vs;this.WriteBytes = this.hex2byte(txt.toString().getBytes());BluetoothGattCharacteristic gg = this.mBluetoothGatt.getService(UUID.fromString(Service_uuid)).getCharacteristic(UUID.fromString(Characteristic_uuid_FUNCTION));gg.setValue(this.WriteBytes);this.mBluetoothGatt.writeCharacteristic(gg);}public void set_PWM2_pulse(int pulse) {String txt = "E8a4";String vs = String.format("%02x", pulse);txt = txt + vs;this.WriteBytes = this.hex2byte(txt.toString().getBytes());BluetoothGattCharacteristic gg = this.mBluetoothGatt.getService(UUID.fromString(Service_uuid)).getCharacteristic(UUID.fromString(Characteristic_uuid_FUNCTION));gg.setValue(this.WriteBytes);this.mBluetoothGatt.writeCharacteristic(gg);}public void set_PWM3_pulse(int pulse) {String txt = "E8a5";String vs = String.format("%02x", pulse);txt = txt + vs;this.WriteBytes = this.hex2byte(txt.toString().getBytes());BluetoothGattCharacteristic gg = this.mBluetoothGatt.getService(UUID.fromString(Service_uuid)).getCharacteristic(UUID.fromString(Characteristic_uuid_FUNCTION));gg.setValue(this.WriteBytes);this.mBluetoothGatt.writeCharacteristic(gg);}public void set_PWM4_pulse(int pulse) {String txt = "E8a6";String vs = String.format("%02x", pulse);txt = txt + vs;this.WriteBytes = this.hex2byte(txt.toString().getBytes());BluetoothGattCharacteristic gg = this.mBluetoothGatt.getService(UUID.fromString(Service_uuid)).getCharacteristic(UUID.fromString(Characteristic_uuid_FUNCTION));gg.setValue(this.WriteBytes);this.mBluetoothGatt.writeCharacteristic(gg);}public void set_PWM_ALL_pulse(int PWM1_pulse, int PWM2_pulse, int PWM3_pulse, int PWM4_pulse) {String txt = "E8a7";String vs = String.format("%02x", PWM1_pulse);txt = txt + vs;vs = String.format("%02x", PWM2_pulse);txt = txt + vs;vs = String.format("%02x", PWM3_pulse);txt = txt + vs;vs = String.format("%02x", PWM4_pulse);txt = txt + vs;this.WriteBytes = this.hex2byte(txt.toString().getBytes());BluetoothGattCharacteristic gg = this.mBluetoothGatt.getService(UUID.fromString(Service_uuid)).getCharacteristic(UUID.fromString(Characteristic_uuid_FUNCTION));gg.setValue(this.WriteBytes);this.mBluetoothGatt.writeCharacteristic(gg);}public void set_AV_OPEN(int p) {String txt = "E9a501";String vs = String.format("%02x", p);txt = txt + vs;this.WriteBytes = this.hex2byte(txt.toString().getBytes());BluetoothGattCharacteristic gg = this.mBluetoothGatt.getService(UUID.fromString(Service_uuid)).getCharacteristic(UUID.fromString(Characteristic_uuid_FUNCTION));gg.setValue(this.WriteBytes);this.mBluetoothGatt.writeCharacteristic(gg);}public void set_AV_PULSE(int p) {String txt = "E9a502";String vs = String.format("%02x", p);txt = txt + vs;this.WriteBytes = this.hex2byte(txt.toString().getBytes());BluetoothGattCharacteristic gg = this.mBluetoothGatt.getService(UUID.fromString(Service_uuid)).getCharacteristic(UUID.fromString(Characteristic_uuid_FUNCTION));gg.setValue(this.WriteBytes);this.mBluetoothGatt.writeCharacteristic(gg);}public void set_LED_Mode(int i) {String txt = "E9b101";String vs = String.format("%02x", i);txt = txt + vs;this.WriteBytes = this.hex2byte(txt.toString().getBytes());BluetoothGattCharacteristic gg = this.mBluetoothGatt.getService(UUID.fromString(Service_uuid)).getCharacteristic(UUID.fromString(Characteristic_uuid_FUNCTION));gg.setValue(this.WriteBytes);this.mBluetoothGatt.writeCharacteristic(gg);}public void set_LED_Brightness(int i) {String txt = "E9b102";String vs = String.format("%02x", i);txt = txt + vs;this.WriteBytes = this.hex2byte(txt.toString().getBytes());BluetoothGattCharacteristic gg = this.mBluetoothGatt.getService(UUID.fromString(Service_uuid)).getCharacteristic(UUID.fromString(Characteristic_uuid_FUNCTION));gg.setValue(this.WriteBytes);this.mBluetoothGatt.writeCharacteristic(gg);}public void set_LED_T_J_F(int i) {String txt = "E9b103";String vs = String.format("%02x", i);txt = txt + vs;this.WriteBytes = this.hex2byte(txt.toString().getBytes());BluetoothGattCharacteristic gg = this.mBluetoothGatt.getService(UUID.fromString(Service_uuid)).getCharacteristic(UUID.fromString(Characteristic_uuid_FUNCTION));gg.setValue(this.WriteBytes);this.mBluetoothGatt.writeCharacteristic(gg);}public void set_LED_Speed(int i) {String txt = "E9b104";String vs = String.format("%02x", i);txt = txt + vs;this.WriteBytes = this.hex2byte(txt.toString().getBytes());BluetoothGattCharacteristic gg = this.mBluetoothGatt.getService(UUID.fromString(Service_uuid)).getCharacteristic(UUID.fromString(Characteristic_uuid_FUNCTION));gg.setValue(this.WriteBytes);this.mBluetoothGatt.writeCharacteristic(gg);}public void set_LED_Custom_LEN(int i) {String txt = "E9b1A0";String vs = String.format("%02x", i);txt = txt + vs;this.WriteBytes = this.hex2byte(txt.toString().getBytes());BluetoothGattCharacteristic gg = this.mBluetoothGatt.getService(UUID.fromString(Service_uuid)).getCharacteristic(UUID.fromString(Characteristic_uuid_FUNCTION));gg.setValue(this.WriteBytes);this.mBluetoothGatt.writeCharacteristic(gg);}public boolean set_LED_Custom1(String dd) {if (dd == null) {return false;} else {int len = dd.length();if (len == 24) {String txt = "E9b1A1";txt = txt + dd;this.WriteBytes = this.hex2byte(txt.toString().getBytes());BluetoothGattCharacteristic gg = this.mBluetoothGatt.getService(UUID.fromString(Service_uuid)).getCharacteristic(UUID.fromString(Characteristic_uuid_FUNCTION));gg.setValue(this.WriteBytes);this.mBluetoothGatt.writeCharacteristic(gg);return true;} else {return false;}}}public boolean set_LED_Custom2(String dd) {if (dd == null) {return false;} else {int len = dd.length();if (len == 24) {String txt = "E9b1A2";txt = txt + dd;this.WriteBytes = this.hex2byte(txt.toString().getBytes());BluetoothGattCharacteristic gg = this.mBluetoothGatt.getService(UUID.fromString(Service_uuid)).getCharacteristic(UUID.fromString(Characteristic_uuid_FUNCTION));gg.setValue(this.WriteBytes);this.mBluetoothGatt.writeCharacteristic(gg);return true;} else {return false;}}}public boolean set_LED_Custom3(String dd) {if (dd == null) {return false;} else {int len = dd.length();if (len == 24) {String txt = "E9b1A3";txt = txt + dd;this.WriteBytes = this.hex2byte(txt.toString().getBytes());BluetoothGattCharacteristic gg = this.mBluetoothGatt.getService(UUID.fromString(Service_uuid)).getCharacteristic(UUID.fromString(Characteristic_uuid_FUNCTION));gg.setValue(this.WriteBytes);this.mBluetoothGatt.writeCharacteristic(gg);return true;} else {return false;}}}public boolean set_LED_Custom4(String dd) {if (dd == null) {return false;} else {int len = dd.length();if (len == 24) {String txt = "E9b1A4";txt = txt + dd;this.WriteBytes = this.hex2byte(txt.toString().getBytes());BluetoothGattCharacteristic gg = this.mBluetoothGatt.getService(UUID.fromString(Service_uuid)).getCharacteristic(UUID.fromString(Characteristic_uuid_FUNCTION));gg.setValue(this.WriteBytes);this.mBluetoothGatt.writeCharacteristic(gg);return true;} else {return false;}}}public boolean set_LED_PAD_color(String dd) {if (dd == null) {return false;} else {int len = dd.length();if (len == 8) {String txt = "E9b1A5";txt = txt + dd;this.WriteBytes = this.hex2byte(txt.toString().getBytes());BluetoothGattCharacteristic gg = this.mBluetoothGatt.getService(UUID.fromString(Service_uuid)).getCharacteristic(UUID.fromString(Characteristic_uuid_FUNCTION));gg.setValue(this.WriteBytes);this.mBluetoothGatt.writeCharacteristic(gg);return true;} else {return false;}}}public void set_LED_OPEN(boolean p) {String txt = "E9b1A9";if (p) {txt = txt + "01";} else {txt = txt + "00";}this.WriteBytes = this.hex2byte(txt.toString().getBytes());BluetoothGattCharacteristic gg = this.mBluetoothGatt.getService(UUID.fromString(Service_uuid)).getCharacteristic(UUID.fromString(Characteristic_uuid_FUNCTION));gg.setValue(this.WriteBytes);this.mBluetoothGatt.writeCharacteristic(gg);}public void Delay_ms(int ms) {try {Thread.currentThread();Thread.sleep((long)ms);} catch (InterruptedException var3) {var3.printStackTrace();}}public Boolean set_uuid(String txt) {if (txt.length() == 36) {String v1 = "";String v2 = "";String v3 = "";String v4 = "";v1 = txt.substring(8, 9);v2 = txt.substring(13, 14);v3 = txt.substring(18, 19);v4 = txt.substring(23, 24);if (v1.equals("-") && v2.equals("-") && v3.equals("-") && v4.equals("-")) {txt = txt.replace("-", "");txt = "AAF1" + txt;this.WriteBytes = this.hex2byte(txt.toString().getBytes());BluetoothGattCharacteristic gg = this.mBluetoothGatt.getService(UUID.fromString(Service_uuid)).getCharacteristic(UUID.fromString(Characteristic_uuid_FUNCTION));gg.setValue(this.WriteBytes);this.mBluetoothGatt.writeCharacteristic(gg);return true;} else {return false;}} else {return false;}}public int get_connected_status(List<BluetoothGattService> gattServices) {boolean jdy_ble_server = false;boolean jdy_ble_ffe1 = false;boolean jdy_ble_ffe2 = false;String LIST_NAME1 = "NAME";String LIST_UUID1 = "UUID";String uuid = null;String unknownServiceString = this.getResources().getString(2131034127);String unknownCharaString = this.getResources().getString(2131034126);ArrayList<HashMap<String, String>> gattServiceData = new ArrayList();ArrayList<ArrayList<HashMap<String, String>>> gattCharacteristicData = new ArrayList();Iterator var13 = gattServices.iterator();while(var13.hasNext()) {BluetoothGattService gattService = (BluetoothGattService)var13.next();HashMap<String, String> currentServiceData = new HashMap();uuid = gattService.getUuid().toString();currentServiceData.put("NAME", SampleGattAttributes.lookup(uuid, unknownServiceString));currentServiceData.put("UUID", uuid);gattServiceData.add(currentServiceData);ArrayList<HashMap<String, String>> gattCharacteristicGroupData = new ArrayList();List<BluetoothGattCharacteristic> gattCharacteristics = gattService.getCharacteristics();ArrayList<BluetoothGattCharacteristic> charas = new ArrayList();if (Service_uuid.equals(uuid)) {jdy_ble_server = true;}Iterator var19 = gattCharacteristics.iterator();while(var19.hasNext()) {BluetoothGattCharacteristic gattCharacteristic = (BluetoothGattCharacteristic)var19.next();charas.add(gattCharacteristic);HashMap<String, String> currentCharaData = new HashMap();uuid = gattCharacteristic.getUuid().toString();currentCharaData.put("NAME", SampleGattAttributes.lookup(uuid, unknownCharaString));currentCharaData.put("UUID", uuid);gattCharacteristicGroupData.add(currentCharaData);if (jdy_ble_server) {if (Characteristic_uuid_TX.equals(uuid)) {jdy_ble_ffe1 = true;} else if (Characteristic_uuid_FUNCTION.equals(uuid)) {jdy_ble_ffe2 = true;}}}gattCharacteristicData.add(gattCharacteristicGroupData);}if (jdy_ble_ffe1 && jdy_ble_ffe2) {return 2;} else if (jdy_ble_ffe1 && !jdy_ble_ffe2) {return 1;} else {return 0;}}private void broadcastUpdate(String action) {Intent intent = new Intent(action);this.sendBroadcast(intent);}private void broadcastUpdate(String action, BluetoothGattCharacteristic characteristic) {Intent intent = new Intent(action);Log.d("getUuid", " len = " + characteristic.getUuid());if (UUID_HEART_RATE_MEASUREMENT.equals(characteristic.getUuid())) {int flag = characteristic.getProperties();boolean format = true;if ((flag & 1) != 0) {format = true;} else {format = true;}} else {byte[] data;if (UUID.fromString(Characteristic_uuid_TX).equals(characteristic.getUuid())) {data = characteristic.getValue();if (data != null && data.length > 0) {intent.putExtra("com.example.bluetooth.le.EXTRA_DATA", data);}} else if (UUID.fromString(Characteristic_uuid_FUNCTION).equals(characteristic.getUuid())) {data = characteristic.getValue();if (data != null && data.length > 0) {intent.putExtra("com.example.bluetooth.le.EXTRA_DATA1", data);}}}this.sendBroadcast(intent);}public IBinder onBind(Intent intent) {return this.mBinder;}public boolean onUnbind(Intent intent) {this.close();return super.onUnbind(intent);}public boolean initialize() {if (this.mBluetoothManager == null) {this.mBluetoothManager = (BluetoothManager)this.getSystemService("bluetooth");if (this.mBluetoothManager == null) {Log.e(TAG, "Unable to initialize BluetoothManager.");return false;}}this.mBluetoothAdapter = this.mBluetoothManager.getAdapter();if (this.mBluetoothAdapter == null) {Log.e(TAG, "Unable to obtain a BluetoothAdapter.");return false;} else {return true;}}public boolean connect(String address) {if (this.mBluetoothAdapter != null && address != null) {if (this.mBluetoothDeviceAddress != null && address.equals(this.mBluetoothDeviceAddress) && this.mBluetoothGatt != null) {Log.d(TAG, "Trying to use an existing mBluetoothGatt for connection.");if (this.mBluetoothGatt.connect()) {this.mConnectionState = 1;return true;} else {return false;}} else {BluetoothDevice device = this.mBluetoothAdapter.getRemoteDevice(address);if (device == null) {Log.w(TAG, "Device not found.  Unable to connect.");return false;} else {this.mBluetoothGatt = device.connectGatt(this, false, this.mGattCallback);Log.d(TAG, "Trying to create a new connection.");this.mBluetoothDeviceAddress = address;this.mConnectionState = 1;return true;}}} else {Log.w(TAG, "BluetoothAdapter not initialized or unspecified address.");return false;}}public void disconnect() {if (this.mBluetoothAdapter != null && this.mBluetoothGatt != null) {this.mBluetoothGatt.disconnect();} else {Log.w(TAG, "BluetoothAdapter not initialized");}}public boolean isconnect() {return this.mBluetoothGatt.connect();}public void close() {if (this.mBluetoothGatt != null) {this.mBluetoothGatt.close();this.mBluetoothGatt = null;}}public void readCharacteristic(BluetoothGattCharacteristic characteristic) {if (this.mBluetoothAdapter != null && this.mBluetoothGatt != null) {this.mBluetoothGatt.readCharacteristic(characteristic);} else {Log.w(TAG, "BluetoothAdapter not initialized");}}public void setCharacteristicNotification(BluetoothGattCharacteristic characteristic, boolean enabled) {if (this.mBluetoothAdapter != null && this.mBluetoothGatt != null) {this.mBluetoothGatt.setCharacteristicNotification(characteristic, enabled);if (UUID_HEART_RATE_MEASUREMENT.equals(characteristic.getUuid())) {BluetoothGattDescriptor descriptor = characteristic.getDescriptor(UUID.fromString(SampleGattAttributes.CLIENT_CHARACTERISTIC_CONFIG));descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);this.mBluetoothGatt.writeDescriptor(descriptor);}} else {Log.w(TAG, "BluetoothAdapter not initialized");}}public List<BluetoothGattService> getSupportedGattServices() {return this.mBluetoothGatt == null ? null : this.mBluetoothGatt.getServices();}public class LocalBinder extends Binder {public LocalBinder() {}public BluetoothLeService getService() {return BluetoothLeService.this;}}public static enum function_type {iBeacon_UUID,iBeacon_Major,iBeacon_Minor,adv_intverl,pin_password,name,GPIO,PWM,Other,Power,RTC;private function_type() {}}
}

安卓蓝牙BluetoothBLE开发JDY-10M相关推荐

  1. 安卓蓝牙bluetooth开发全解

    全栈工程师开发手册 (作者:栾鹏) 安卓教程全解 安卓蓝牙开发全解.启动蓝牙.启动可发现机制.广播监听蓝牙状态.广播监听蓝牙可发现机制状态.发现远程蓝牙设备.蓝牙设备作为服务器端.蓝牙设备作为客户端. ...

  2. 基于经典蓝牙的安卓蓝牙APP开发(基于蓝牙2.0开发,例:HC-05)

    基于经典蓝牙的安卓蓝牙开发-串口 一.展现广播的三种方式 1.通知: 2.对话框: 3.消息提示框 2.在使用Android蓝牙适配器中的startDiscovery需要先打开定位服务 3.在连接蓝牙 ...

  3. 基于蓝牙(HC-05)的安卓蓝牙 APP开发

    前言 ​​​​由于想做一个蓝牙小车,就随便找了点开发蓝牙app的资料教程.这边呢也是一个能快速弄一个app出来,比较简单.一小时之内可以弄好了. 一.开发网站 这儿-->传送门 二.app界面设 ...

  4. 关于便携式打印机程序开发(一、原生安卓蓝牙调用)

    关于便携式打印机程序开发(一.原生安卓蓝牙调用) 综述 软硬件 SDK集成到项目 CPCL协议开发 综述 使用android程序,调用蓝牙,和打印机配对之后,可以连接打印机,通过(WIFI.蓝牙.US ...

  5. 安卓蓝牙开发的几个版本区别

    不得不说,这有时候真的坑爹. 你 搜索安卓蓝牙开发,有的大谈4.0结果还是什么socket那些,这是安卓4.0,不是蓝牙4.0啊 安卓4.2以及以下才是这种 4.3以后就可以ble了,低功耗,更碉堡 ...

  6. 基于QT的安卓手机蓝牙APP开发

    摘要:前段时间用QT写了一个串口调试助手,感觉还可以.因为QT是跨平台的,同样一套代码可以在windows上面跑,也可以在linux上面跑,也可以在安卓手机上面跑.而且不需要修改任何东西,编译器会自动 ...

  7. Qt on Android 蓝牙通信开发

    版权声明:本文为MULTIBEANS ORG研发跟随文章,未经MLT ORG允许不得转载. 最近做项目,需要开发安卓应用,实现串口的收发,目测CH340G在安卓手机上非常麻烦,而且驱动都是Java版本 ...

  8. 谷歌修复安卓蓝牙组件中无需用户交互的 bug

    聚焦源代码安全,网罗国内外最新资讯! 编译:奇安信代码卫士团队 本周,谷歌修复了安卓蓝牙组件中的一个严重缺陷.如未被修复,则该漏洞可在无需用户交互的情况下遭利用,甚至可被用于自传播蓝牙蠕虫. 谷歌已经 ...

  9. 安卓蓝牙操作+蓝牙工具类

    由于前段时间,需要蓝牙操作一些东西.但是没有写过蓝牙连接与蓝牙操作等一系列的东西. 然后就去网上找找大家写的.到现在.已经结束了这个蓝牙的开发. 安卓端蓝牙操作.主要需要如下类 BluetoothAd ...

  10. android苹果蓝牙版本,苹果蓝牙和安卓蓝牙能连吗

    大家好,我是时间财富网智能客服时间君,上述问题将由我为大家进行解答. 苹果蓝牙和安卓蓝牙能连: 1.首先,在的苹果手机的设置,找到蓝牙,然后打开它: 2.接着,拿起安卓手机,找到设置里的蓝牙,点击一下 ...

最新文章

  1. 以AI制作AI,当AutoML加入AI研究员内卷大潮
  2. 关于路径的使用,assi下载和
  3. 每日一皮:最真实的现代互联网商业模式
  4. WCF+REST 返回Json数据有双引号怎么去掉
  5. 【bzoj2423】最长公共子序列[HAOI2010](dp)
  6. 让“云”无处不在-Citrix Xenserver之三 license server
  7. 简书 php三级联动,JS 实现三级联动
  8. android uri db,Android ContentProvider封装数据库和文件读写总结
  9. 小程序 Typescript 最佳实践
  10. java 取Blob转为String
  11. ajax获取nodejs的值,jquery - NodeJS如何获取服务器中的数据,通过POST从jquery ajax调用发送 - 堆栈内存溢出...
  12. 【perl】LWP module
  13. 【工匠大道】博客园小技巧
  14. JavaScript题 - 应用
  15. GNS3 VM 的安装使用和路由器的添加
  16. devexpress,dotnetbar控件
  17. android开机画面在uboot里吗,iTOP-6818开发板-Android5.1修改uboot和内核开机LOGO
  18. 服务器虚拟化的主要特点,网络虚拟化的七大特征
  19. TienLen游戏模型、算法,类似斗地主游戏算法
  20. 【python】pdf转png

热门文章

  1. 佳能 6D Mark II与 90D 对比评测
  2. pytorch(11)-- crnn 车牌端到端识别
  3. 【生信技能树】GEO数据库挖掘 P6 5了解矩阵
  4. UI设计师(界面设计)面试题
  5. 12306bycloud,免费开源抢票软件,无需安装,全平台可用
  6. JSON-RPC是什么东西
  7. 人人商城小程序微信支付配置
  8. AD20导出Gerber教程
  9. tftp: timeout
  10. 常见面试题汇总 —— C语言