安卓蓝牙BluetoothBLE开发JDY-10M

 

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

介绍一下

JDY-10M蓝牙模块:

安卓蓝牙BluetoothBLE开发JDY-10M_第1张图片

安卓蓝牙BluetoothBLE开发JDY-10M_第2张图片

手机系统为安卓9版本。

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

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

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

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

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

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

蓝牙概述

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

扫描界面放一个listview。

假定名字为SCAN_VIEW.xml



    

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

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

假定名字为ITEM_BLE_LIST.xml


    
    

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

新建一个menu

假定名字为SCAN_MAIN.xml.

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




    

    

    

扫描界面代码:

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;
    @Override
    public 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() {
			@Override
			public 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;
		}
	}
    @Override
    public 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;
    }

    @Override
    public 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() {
                @Override
                public 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() {

		@Override
		public void onLeScan(final BluetoothDevice device, int rssi,
				byte[] scanRecord) {
			runOnUiThread(new Runnable() {
				@Override
				public void run() {
					mDevListAdapter.addDevice(device);
					mDevListAdapter.notifyDataSetChanged();
				}
			});
		}
	};

	@Override
	protected void onResume() {//打开APP时扫描设备
		super.onResume();
		scanLeDevice(true);
	}

	@Override
	protected void onPause() {//停止扫描
		super.onPause();
		scanLeDevice(false);
	}

    //自定义DeviceListAdapter类,用于显示数据,清除数据
	class DeviceListAdapter extends BaseAdapter {
		private List mBleArray;
		private ViewHolder viewHolder;

		public DeviceListAdapter() {
			mBleArray = new ArrayList();
		}

		public void addDevice(BluetoothDevice device) {
			if (!mBleArray.contains(device)) {
				mBleArray.add(device);
			}
		}
		public void clear(){
			mBleArray.clear();
		}

		@Override
		public int getCount() {
			return mBleArray.size();
		}

		@Override
		public BluetoothDevice getItem(int position) {
			return mBleArray.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public 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。可能是有引用的资源没有,导致无法显示。下图是正常,没有导入成功就是空白的。

安卓蓝牙BluetoothBLE开发JDY-10M_第3张图片

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

创建第二个界面

如下图所示

安卓蓝牙BluetoothBLE开发JDY-10M_第4张图片





    

        

        
    

    

        

        
    

    

        

        

        
    

    

        
    

    

        

        

        
    

    

        
        
    

    

        
    

    

        

 

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

也是在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> mGattCharacteristics =
            new ArrayList>();
    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() {

        @Override
        public 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);
        }

        @Override
        public 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() {
        @Override
        public 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() {
                @Override
                public 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进制数
    }
    @Override
    protected 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 1002
        send_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 1002
        clear_button.setOnClickListener(listener);


        txd_txt=(EditText)findViewById(R.id.tx_text);
        //1002 data
        txd_txt.setText("");
        txd_txt.clearFocus();

        rx_data_id_1=(EditText)findViewById(R.id.rx_data_id_1);
        //1002 data
        rx_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(){
            @Override
            public void onCheckedChanged(CompoundButton buttonView,
                                         boolean isChecked) {
                // TODO Auto-generated method stub
                if(isChecked){
                    rx_hex = true;
                }else{
                    rx_hex = false;
                }
            }
        });
        checkBox1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener(){
            @Override
            public void onCheckedChanged(CompoundButton buttonView,
                                         boolean isChecked) {
                // TODO Auto-generated method stub
                if(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(){
            @Override
            public void onCheckedChanged(CompoundButton buttonView,
                                         boolean isChecked) {
                // TODO Auto-generated method stub
                if(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()
        {
            @Override
            public 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的列表index
    public 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() {

        @Override
        public void run() {
            // 发送数据
            Message message = new Message();
            message.what = 1;
            handler.sendMessage(message);
        }
    };

    ToggleButton.OnClickListener OnClickListener_listener = new ToggleButton.OnClickListener()
    {
        @Override
        public 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;
            }
        }

    };
    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }


    @Override
    public 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() {
            @Override
            public 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 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;
    }
    @Override
    protected 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 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> 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 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> gattServiceData = new ArrayList();
        ArrayList>> gattCharacteristicData = new ArrayList();
        Iterator var13 = gattServices.iterator();

        while(var13.hasNext()) {
            BluetoothGattService gattService = (BluetoothGattService)var13.next();
            HashMap currentServiceData = new HashMap();
            uuid = gattService.getUuid().toString();
            currentServiceData.put("NAME", SampleGattAttributes.lookup(uuid, unknownServiceString));
            currentServiceData.put("UUID", uuid);
            gattServiceData.add(currentServiceData);
            ArrayList> gattCharacteristicGroupData = new ArrayList();
            List gattCharacteristics = gattService.getCharacteristics();
            ArrayList 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 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 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() {
        }
    }
}

 

你可能感兴趣的:(笔记,安卓)