当前位置:   article > 正文

android 蓝牙模块的串口通信_andoird bluetoothdevice 串口通讯

andoird bluetoothdevice 串口通讯


一直先想做一个遥控车,正好放假了,所以这些日子有时间,然后就搜集资料,找到一个博客,忘记是哪个了博主写的了,然后就试这写一下,

做完后一运行就是就Bug ,就是当终端蓝牙开启的时候,打开这个软件时,Android 顿时弹出来个大的ANR ,然后我改了改,没这种毛病了,然后又添了一些,比如当在蓝牙关闭的状态上打开软件,软件自动会打开蓝牙。

挺好玩的的。


一共分两个Activityu第一个是搜索蓝牙进行配对操作,第二个就是发送cdm了。

我用的是Android Studio写的所以不必担心添加权限的问题,如果你是用Eclipse写的那么一定不要忘了添加这两条权限:

<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>

在打开、关闭搜索,配对中主要是用到了两个类:BlueToothAdapter,和 BlueToothSocket这两个类。

里面有一个UUID也不知道是什么东西查API解释是UUID是128位的不可变表示全局惟一标识符(UUID)。什么魔鬼??望指教。

看代码吧。


一、Mainactivity.xml文件往下看的

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <RelativeLayout
  3. xmlns:android="http://schemas.android.com/apk/res/android"
  4. xmlns:tools="http://schemas.android.com/tools"
  5. android:layout_width="match_parent"
  6. android:layout_height="match_parent"
  7. android:paddingBottom="@dimen/activity_vertical_margin"
  8. android:paddingLeft="@dimen/activity_horizontal_margin"
  9. android:paddingRight="@dimen/activity_horizontal_margin"
  10. android:paddingTop="@dimen/activity_vertical_margin"
  11. tools:context="com.example.hejingzhou.newbuledemo.MainActivity"
  12. android:background="@drawable/bac">
  13. <Switch
  14. android:layout_width="50dp"
  15. android:layout_height="wrap_content"
  16. android:id="@+id/switchOpenAndClose"
  17. android:textOff="关闭"
  18. android:textOn="打开"
  19. android:checked="false"
  20. android:layout_alignParentTop="true"
  21. android:layout_toRightOf="@+id/textView"
  22. android:layout_toEndOf="@+id/textView"/>
  23. <Button
  24. android:layout_width="match_parent"
  25. android:layout_height="wrap_content"
  26. android:text="允许本设备对外可见"
  27. android:id="@+id/buttonVisible"
  28. android:layout_below="@+id/switchOpenAndClose"
  29. android:layout_centerHorizontal="true"/>
  30. <Button
  31. android:layout_width="match_parent"
  32. android:layout_height="wrap_content"
  33. android:text="搜索其他的设备"
  34. android:id="@+id/buttonSeraveDevice"
  35. android:layout_below="@+id/buttonVisible"
  36. android:layout_centerHorizontal="true"/>
  37. <Button
  38. android:layout_width="match_parent"
  39. android:layout_height="wrap_content"
  40. android:text="退出程序"
  41. android:id="@+id/buttonExit"
  42. android:layout_alignParentBottom="true"
  43. android:layout_alignParentLeft="true"
  44. android:layout_alignParentStart="true"/>
  45. <TextView
  46. android:layout_width="wrap_content"
  47. android:layout_height="wrap_content"
  48. android:textAppearance="?android:attr/textAppearanceLarge"
  49. android:text="蓝牙开关"
  50. android:textColor="#FFFFFF"
  51. android:id="@+id/textView"
  52. android:layout_alignParentTop="true"
  53. android:layout_alignParentLeft="true"
  54. android:layout_alignParentStart="true"/>
  55. <ListView
  56. android:layout_width="wrap_content"
  57. android:layout_height="wrap_content"
  58. android:id="@+id/listViewShow"
  59. android:layout_centerHorizontal="true"
  60. android:layout_below="@+id/buttonSeraveDevice"
  61. android:layout_above="@+id/buttonExit"/>
  62. </RelativeLayout>


二、MainActivity.java

  1. <span style="font-family:SimSun;"><span style="color:#2b2b2b;"><span style="font-size: 18px; line-height: 27px; background-color: rgb(248, 248, 248);"><strong>package com.example.hejingzhou.newbuledemo;
  2. </strong></span></span></span><span style="font-size:18px;">import android.bluetooth.BluetoothAdapter;
  3. import android.bluetooth.BluetoothDevice;
  4. import android.bluetooth.BluetoothServerSocket;
  5. import android.bluetooth.BluetoothSocket;
  6. import android.content.BroadcastReceiver;
  7. import android.content.Context;
  8. import android.content.Intent;
  9. import android.content.IntentFilter;
  10. import android.os.*;
  11. import android.os.Process;
  12. import android.support.v7.app.AppCompatActivity;
  13. import android.util.Log;
  14. import android.view.View;
  15. import android.widget.AdapterView;
  16. import android.widget.ArrayAdapter;
  17. import android.widget.Button;
  18. import android.widget.CompoundButton;
  19. import android.widget.ListView;
  20. import android.widget.Switch;
  21. import android.widget.Toast;
  22. import java.io.IOException;
  23. import java.lang.reflect.InvocationTargetException;
  24. import java.lang.reflect.Method;
  25. import java.util.ArrayList;
  26. import java.util.List;
  27. import java.util.UUID;
  28. public class MainActivity extends AppCompatActivity {
  29. private Switch aSwitch;
  30. private Button buttonVisible,buttonSearch,buttonExit;
  31. private ListView listView;
  32. private Handler handler;
  33. private BluetoothAdapter bluetoothAdapter;
  34. static final String SPP_UUID = "00001101-0000-1000-8000-00805F9B34FB";
  35. private UUID uuid;
  36. private List<String> listDevice = new ArrayList<>();
  37. private ArrayAdapter<String> adapterDevice;
  38. private static BluetoothSocket socket;
  39. public static BluetoothSocket bluetoothSocket;
  40. private static AcceptThread acceptThread;
  41. @Override
  42. protected void onCreate(Bundle savedInstanceState) {
  43. super.onCreate(savedInstanceState);
  44. setContentView(R.layout.activity_main);
  45. findViewById();
  46. OnClick();
  47. bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
  48. uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
  49. InitBlueTooth();
  50. }
  51. /************************************************************************************************************/
  52. private void OnClick() {
  53. //Switch开关
  54. aSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
  55. @Override
  56. public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
  57. if (isChecked == true) {
  58. if (bluetoothAdapter.getState() == BluetoothAdapter.STATE_ON) {
  59. return;
  60. } else if (bluetoothAdapter.getState() == BluetoothAdapter.STATE_OFF) {
  61. bluetoothAdapter.enable();
  62. try {
  63. Thread.sleep(3000);
  64. } catch (InterruptedException e) {
  65. e.printStackTrace();
  66. }
  67. if (bluetoothAdapter.getState() == BluetoothAdapter.STATE_ON) {
  68. Toast.makeText(MainActivity.this, "蓝牙已打开", Toast.LENGTH_SHORT).show();
  69. }
  70. /***********修改修改**********/
  71. try {
  72. acceptThread = new AcceptThread();
  73. handler = new Handler() {
  74. public void handle(Message message) {
  75. switch (message.what) {
  76. case 0:
  77. acceptThread.start();
  78. }
  79. }
  80. };
  81. } catch (Exception e) {
  82. Toast.makeText(MainActivity.this, "服务监听出错", Toast.LENGTH_SHORT).show();
  83. }
  84. }
  85. } else if (isChecked = false) {
  86. bluetoothAdapter.disable();
  87. if (bluetoothAdapter.getState() == BluetoothAdapter.STATE_OFF)
  88. Toast.makeText(MainActivity.this, "蓝牙已关闭", Toast.LENGTH_SHORT).show();
  89. }
  90. }
  91. });
  92. //可见性Button
  93. buttonVisible.setOnClickListener(new View.OnClickListener() {
  94. @Override
  95. public void onClick(View v) {
  96. Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
  97. discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
  98. startActivity(discoverableIntent);
  99. }
  100. });
  101. //搜索设备
  102. buttonSearch.setOnClickListener(new View.OnClickListener() {
  103. @Override
  104. public void onClick(View v) {
  105. setTitle("本机蓝牙地址" + bluetoothAdapter.getAddress());
  106. listDevice.clear();
  107. bluetoothAdapter.startDiscovery();//启动搜索其他蓝牙设备
  108. }
  109. });
  110. //退出Button
  111. buttonExit.setOnClickListener(new View.OnClickListener() {
  112. @Override
  113. public void onClick(View v) {
  114. if(bluetoothSocket != null)
  115. {
  116. try {
  117. bluetoothSocket.close();
  118. } catch (IOException e) {
  119. e.printStackTrace();
  120. }
  121. MainActivity.this.finish();
  122. }
  123. }
  124. });
  125. }
  126. /************************************************************************************************************/
  127. private void InitBlueTooth() {
  128. Toast.makeText(MainActivity.this,"正在初始化软件,请稍等...",Toast.LENGTH_SHORT).show();
  129. /*if(bluetoothAdapter == null)
  130. {
  131. Toast.makeText(MainActivity.this,"您的蓝牙不可用,请查验您的手机是否具有此功能",Toast.LENGTH_LONG).show();
  132. return;
  133. }
  134. else
  135. {*/
  136. if(bluetoothAdapter.getState() == BluetoothAdapter.STATE_OFF)
  137. {
  138. aSwitch.setChecked(false);
  139. bluetoothAdapter.enable();
  140. if(bluetoothAdapter.getState() == BluetoothAdapter.STATE_ON)
  141. {
  142. Toast.makeText(MainActivity.this,"成功帮您打开蓝牙",Toast.LENGTH_LONG).show();
  143. }else
  144. {
  145. Toast.makeText(MainActivity.this,"打开蓝牙失败,请手动打开您的蓝牙",Toast.LENGTH_LONG).show();
  146. }
  147. }else if(bluetoothAdapter.getState() == bluetoothAdapter.STATE_ON)
  148. {
  149. acceptThread = new AcceptThread();
  150. handler = new Handler()
  151. {
  152. public void handleMessage(Message msg)
  153. {
  154. switch (msg.what)
  155. {
  156. case 0:
  157. acceptThread.start();
  158. break;
  159. }
  160. }
  161. };
  162. }
  163. //注册Receiver蓝牙设备的相关结果
  164. //IntentFilter结构化的描述意图值匹配。IntentFilter可以匹配操作、类别和数据(通过其类型、计划和/或路径)的意图。它还包括一个“优先级”值用于订单多个匹配过滤器。
  165. IntentFilter intentFilter = new IntentFilter();
  166. intentFilter.addAction(BluetoothDevice.ACTION_FOUND);
  167. intentFilter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);//广播操作:指示远程设备上的键状态的改变
  168. intentFilter.addAction(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED);//广播操作:指示本地适配器的蓝牙扫描模式已经改变。
  169. intentFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);//广播操作:当地蓝牙适配器的状态已更改。
  170. registerReceiver(serachDevices,intentFilter);
  171. // }
  172. }
  173. /**************************************************************************************************************/
  174. private void findViewById() {
  175. aSwitch = (Switch)findViewById(R.id.switchOpenAndClose);
  176. buttonVisible = (Button)findViewById(R.id.buttonVisible);
  177. buttonSearch = (Button)findViewById(R.id.buttonSeraveDevice);
  178. buttonExit = (Button)findViewById(R.id.buttonExit);
  179. listView = (ListView)findViewById(R.id.listViewShow);
  180. adapterDevice = new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_list_item_1,listDevice);
  181. listView.setAdapter(adapterDevice);
  182. listView.setOnItemClickListener(new ItemClickEvent());//设置ListView 的单击监听
  183. }
  184. /*************************************************************************************************************/
  185. class AcceptThread extends Thread
  186. {
  187. private final BluetoothServerSocket serverSocket;//蓝牙服务套接口
  188. public AcceptThread()
  189. {
  190. BluetoothServerSocket BTServerSocket = null;
  191. try {
  192. Method listenMethod = bluetoothAdapter.getClass().getMethod("listenUsingRfcommOn",new Class[]{int.class});
  193. BTServerSocket = (BluetoothServerSocket)listenMethod.invoke(bluetoothAdapter,Integer.valueOf(1));
  194. } catch (NoSuchMethodException e) {
  195. e.printStackTrace();
  196. } catch (InvocationTargetException e) {
  197. e.printStackTrace();
  198. } catch (IllegalAccessException e) {
  199. e.printStackTrace();
  200. }
  201. serverSocket = BTServerSocket;
  202. }
  203. public void run()
  204. {
  205. while (true)
  206. {
  207. try {
  208. socket = serverSocket.accept();
  209. Log.e("MainActivity","socket = serverSocket.accept();错误");
  210. } catch (IOException e) {
  211. break;
  212. }
  213. if(socket != null)
  214. {
  215. manageConnectedSocket();
  216. try {
  217. serverSocket.close();
  218. } catch (IOException e) {
  219. e.printStackTrace();
  220. }
  221. break;
  222. }
  223. }
  224. Message message = new Message();
  225. message.what = 0;
  226. handler.sendMessage(message);
  227. }
  228. public void cancel()
  229. {
  230. try {
  231. serverSocket.close();
  232. } catch (IOException e) {
  233. Log.e("MainActivity","注销错误");
  234. }
  235. }
  236. }
  237. /*************************************************************************************************************/
  238. class ItemClickEvent implements AdapterView.OnItemClickListener {
  239. @Override
  240. public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
  241. String str = listDevice.get(position);
  242. String[] values = str.split("\\|");
  243. String address = values[1];
  244. Log.i("address",values[1]);
  245. uuid = UUID.fromString(SPP_UUID);
  246. Log.i("uuid",uuid.toString());
  247. BluetoothDevice BtDev = bluetoothAdapter.getRemoteDevice(address);//getRemoteDevice获取BluetoothDevice对象从给定的蓝牙硬件地址
  248. Log.i("获取的蓝牙硬件对象"," "+BtDev);
  249. Method method;
  250. try {
  251. method = BtDev.getClass().getMethod("createRfcommSocket",new Class[]{int.class});
  252. bluetoothSocket = (BluetoothSocket) method.invoke(BtDev,Integer.valueOf(1));
  253. } catch (NoSuchMethodException e) {
  254. e.printStackTrace();
  255. } catch (InvocationTargetException e) {
  256. e.printStackTrace();
  257. } catch (IllegalAccessException e) {
  258. e.printStackTrace();
  259. }
  260. bluetoothAdapter.cancelDiscovery();//对蓝牙进行信号注销
  261. try {
  262. bluetoothSocket.connect();//蓝牙配对
  263. Toast.makeText(MainActivity.this,"连接成功进入控制界面",Toast.LENGTH_SHORT).show();
  264. Intent intent = new Intent();
  265. intent.setClass(MainActivity.this, SendMessageActivity.class);
  266. startActivity(intent);
  267. } catch (IOException e) {
  268. e.printStackTrace();
  269. Toast.makeText(MainActivity.this,"连接失败",Toast.LENGTH_SHORT).show();
  270. }
  271. }
  272. }
  273. /*************************************************************************************************************/
  274. /**
  275. * 基类代码,将收到发送的意图sendBroadcast()。
  276. */
  277. private BroadcastReceiver serachDevices = new BroadcastReceiver() {
  278. @Override
  279. public void onReceive(Context context, Intent intent) {
  280. String action = intent.getAction();
  281. Bundle bundle = intent.getExtras();
  282. Object[] listName = bundle.keySet().toArray();
  283. //显示收到的消息及细节
  284. for(int i = 0;i < listName.length;i++)
  285. {
  286. String keyName = listName[i].toString();
  287. Log.i(keyName,String.valueOf(bundle.get(keyName)));
  288. }
  289. if(BluetoothDevice.ACTION_FOUND.equals(action))
  290. {
  291. BluetoothDevice BTDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
  292. String str = BTDevice.getName()+"|"+BTDevice.getAddress();
  293. if(listDevice.indexOf(str) == -1)//indexOf检索字符串,如果为null返回-1
  294. {
  295. listDevice.add(str);
  296. }
  297. adapterDevice.notifyDataSetChanged();//每次改变刷新一下自己
  298. }
  299. }
  300. };
  301. /*************************************************************************************************************/
  302. @Override
  303. protected void onDestroy() {
  304. this.unregisterReceiver(serachDevices);
  305. super.onDestroy();
  306. android.os.Process.killProcess(Process.myPid());//杀死Pid
  307. acceptThread.cancel();
  308. acceptThread.destroy();
  309. }
  310. /*************************************************************************************************************/
  311. private void manageConnectedSocket()
  312. {
  313. bluetoothSocket = socket;
  314. Intent newActivity = new Intent();
  315. newActivity.setClass(MainActivity.this,SendMessageActivity.class);
  316. startActivity(newActivity);
  317. }
  318. }</span><span style="font-family:SimSun;"><span style="color:#2b2b2b;"><span style="font-size: 18px; line-height: 27px; background-color: rgb(248, 248, 248);"><strong>
  319. </strong></span></span></span>


三、sendMessageActivity.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    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:background="@drawable/ee"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    tools:context="com.example.hejingzhou.newbuledemo.SendMessageActivity">

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:text="控制界面"
        android:textAppearance="?android:attr/textAppearanceLarge"/>

    <TextView
        android:id="@+id/textView3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_below="@+id/textView2"
        android:layout_marginTop="42dp"
        android:text="请选择通信对象"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:textSize="15dp"/>

    <RadioGroup
        android:id="@+id/radioGroup"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_alignBottom="@+id/textView3"
        android:layout_alignLeft="@+id/textView2"
        android:layout_alignStart="@+id/textView2"
        android:layout_alignTop="@+id/textView3"
        android:orientation="horizontal">

        <RadioButton
            android:id="@+id/radioPC"
            android:checked="true"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="PC"/>

        <RadioButton
            android:id="@+id/radioMobile"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Mobile"/>
    </RadioGroup>

    <TextView
        android:id="@+id/textView4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_below="@+id/textView3"
        android:layout_marginTop="62dp"
        android:text="继电器1"/>

    <ToggleButton
        android:id="@+id/toggleButton"
        android:layout_width="75dp"
        android:layout_height="35dp"
        android:checked="false"
        android:layout_alignBottom="@+id/textView4"
        android:layout_toEndOf="@+id/textView4"
        android:layout_toRightOf="@+id/textView4"
        android:text="New ToggleButton"/>

    <TextView
        android:id="@+id/textView5"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/toggleButton"
        android:layout_alignLeft="@+id/radioGroup"
        android:layout_alignStart="@+id/radioGroup"
        android:layout_marginLeft="38dp"
        android:layout_marginStart="38dp"
        android:text="继电器2"/>

    <ToggleButton
        android:id="@+id/toggleButton2"
        android:layout_width="75dp"
        android:layout_height="35dp"
        android:checked="false"
        android:layout_alignBottom="@+id/textView5"
        android:layout_toEndOf="@+id/textView2"
        android:layout_toRightOf="@+id/textView2"
        android:text="New ToggleButton"/>

    <TextView
        android:id="@+id/textView6"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/textView4"
        android:layout_marginTop="40dp"
        android:layout_toLeftOf="@+id/toggleButton"
        android:layout_toStartOf="@+id/toggleButton"
        android:text="继电器3"/>

    <ToggleButton
        android:id="@+id/toggleButton3"
        android:layout_width="75dp"
        android:layout_height="35dp"
        android:checked="false"
        android:layout_alignBottom="@+id/textView6"
        android:layout_toEndOf="@+id/textView6"
        android:layout_toRightOf="@+id/textView6"
        android:text="New ToggleButton"/>

    <TextView
        android:id="@+id/textView7"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/textView5"
        android:layout_alignStart="@+id/textView5"
        android:layout_alignTop="@+id/textView6"
        android:text="继电器4"/>

    <ToggleButton
        android:id="@+id/toggleButton4"
        android:layout_width="75dp"
        android:layout_height="35dp"
        android:checked="false"
        android:layout_alignBottom="@+id/toggleButton3"
        android:layout_toEndOf="@+id/textView7"
        android:layout_toRightOf="@+id/textView7"
        android:text="New ToggleButton"/>


    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/editTextreceive"
        android:hint="接收区"
        android:layout_above="@+id/editTextsend"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true"/>

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/editTextsend"
        android:hint="发送区"
        android:layout_above="@+id/buttonsend"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true"/>

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="发送"
        android:id="@+id/buttonsend"
        android:layout_above="@+id/buttonback"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"/>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="返回"
        android:id="@+id/buttonback"
        android:layout_alignParentBottom="true"
        android:layout_alignRight="@+id/textView3"
        android:layout_alignEnd="@+id/textView3"/>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="关闭"
        android:id="@+id/buttonclose"
        android:layout_alignTop="@+id/buttonback"
        android:layout_toRightOf="@+id/textView7"
        android:layout_toEndOf="@+id/textView7"/>

</RelativeLayout>

四、sendMessageActivity.Java

  1. package com.example.hejingzhou.newbuledemo;
  2. <span style="font-size:18px;">
  3. import android.os.Message;
  4. import android.support.v7.app.AppCompatActivity;
  5. import android.os.Bundle;
  6. import android.util.Log;
  7. import android.view.View;
  8. import android.widget.Button;
  9. import android.widget.CompoundButton;
  10. import android.widget.EditText;
  11. import android.widget.RadioButton;
  12. import android.widget.RadioGroup;
  13. import android.widget.TextView;
  14. import android.widget.Toast;
  15. import android.widget.ToggleButton;
  16. import java.io.IOException;
  17. import java.io.InputStream;
  18. import java.io.OutputStream;
  19. import java.io.UnsupportedEncodingException;
  20. import java.util.logging.Handler;
  21. public class SendMessageActivity extends AppCompatActivity implements RadioGroup.OnCheckedChangeListener {
  22. private RadioGroup radioGroup;
  23. private RadioButton radioPc, radioMo;
  24. private ToggleButton TB1, TB2, TB3, TB4;
  25. private EditText EtReceive, EtSend;
  26. private Button BtSend, BtBack, BtClose;
  27. private android.os.Handler handler;
  28. private String encodeType = "GBK";
  29. private boolean isRecording = false;
  30. private OutputStream outputStream = null;
  31. private ConnectedThread connectedThread;
  32. @Override
  33. protected void onCreate(Bundle savedInstanceState) {
  34. super.onCreate(savedInstanceState);
  35. setContentView(R.layout.activity_send_message);
  36. findViewById();
  37. StartThread();
  38. onClickListener();
  39. }
  40. private void onClickListener() {
  41. BtClose.setOnClickListener(new View.OnClickListener() {
  42. @Override
  43. public void onClick(View v) {
  44. try {
  45. MainActivity.bluetoothSocket.close();//关闭蓝牙接口
  46. connectedThread.Stop();
  47. setTitle("蓝牙连接断开");
  48. } catch (IOException e) {
  49. e.printStackTrace();
  50. }
  51. }
  52. });
  53. BtBack.setOnClickListener(new View.OnClickListener() {
  54. @Override
  55. public void onClick(View v) {
  56. SendMessageActivity.this.finish();
  57. }
  58. });
  59. TB1.setOnClickListener(new View.OnClickListener() {
  60. @Override
  61. public void onClick(View v) {
  62. if (TB1.isChecked() == false) {
  63. sendMessage("11");
  64. } else if (TB1.isChecked() == true) {
  65. sendMessage("10");
  66. }
  67. }
  68. });
  69. TB2.setOnClickListener(new View.OnClickListener() {
  70. @Override
  71. public void onClick(View v) {
  72. if (TB2.isChecked() == false) {
  73. sendMessage("21");
  74. } else if (TB2.isChecked() == true) {
  75. sendMessage("20");
  76. }
  77. }
  78. });
  79. TB3.setOnClickListener(new View.OnClickListener() {
  80. @Override
  81. public void onClick(View v) {
  82. if (TB3.isChecked() == false) {
  83. sendMessage("31");
  84. } else if (TB3.isChecked() == true) {
  85. sendMessage("30");
  86. }
  87. }
  88. });
  89. TB4.setOnClickListener(new View.OnClickListener() {
  90. @Override
  91. public void onClick(View v) {
  92. if (TB4.isChecked() == false) {
  93. sendMessage("41");
  94. } else if (TB4.isChecked() == true) {
  95. sendMessage("40");
  96. }
  97. }
  98. });
  99. BtSend.setOnClickListener(new View.OnClickListener() {
  100. @Override
  101. public void onClick(View v) {
  102. String infoSend = EtSend.getText().toString();
  103. sendMessage(infoSend);
  104. setTitle("发送成功");
  105. }
  106. });
  107. }
  108. public void sendMessage(String str) {
  109. try {
  110. outputStream = MainActivity.bluetoothSocket.getOutputStream();
  111. } catch (IOException e) {
  112. Toast.makeText(getApplicationContext(), "输出流失败", Toast.LENGTH_SHORT);
  113. }
  114. byte[] msgBuffer = null;
  115. try {
  116. msgBuffer = str.getBytes(encodeType);
  117. } catch (UnsupportedEncodingException e) {
  118. e.printStackTrace();
  119. Log.e("decode 错误","编码异常",e);
  120. }
  121. try {
  122. outputStream.write(msgBuffer);
  123. setTitle("成功发送命令");
  124. Log.i("成功发送命令"," "+str);
  125. } catch (IOException e) {
  126. Toast.makeText(getApplicationContext(),"发送命令失败",Toast.LENGTH_SHORT);
  127. }
  128. }
  129. /*public static void setEditTextEnable(TextView view,Boolean able){
  130. // view.setTextColor(R.color.read_only_color); //设置只读时的文字颜色
  131. if (view instanceof android.widget.EditText){
  132. view.setCursorVisible(able); //设置输入框中的光标不可见
  133. view.setFocusable(able); //无焦点
  134. view.setFocusableInTouchMode(able); //触摸时也得不到焦点
  135. }
  136. }*/
  137. @Override
  138. protected void onDestroy() {
  139. try {
  140. MainActivity.bluetoothSocket.close();
  141. } catch (IOException e) {
  142. e.printStackTrace();
  143. }
  144. super.onDestroy();
  145. }
  146. private void StartThread() {
  147. connectedThread = new ConnectedThread();
  148. handler = new MyHandler();
  149. connectedThread.Start();
  150. }
  151. private void findViewById() {
  152. radioGroup = (RadioGroup) findViewById(R.id.radioGroup);
  153. radioPc = (RadioButton) findViewById(R.id.radioPC);
  154. radioMo = (RadioButton) findViewById(R.id.radioMobile);
  155. TB1 = (ToggleButton) findViewById(R.id.toggleButton);
  156. TB2 = (ToggleButton) findViewById(R.id.toggleButton2);
  157. TB3 = (ToggleButton) findViewById(R.id.toggleButton3);
  158. TB4 = (ToggleButton) findViewById(R.id.toggleButton4);
  159. EtReceive = (EditText)findViewById(R.id.editTextreceive);
  160. EtSend = (EditText)findViewById(R.id.editTextsend);
  161. BtSend = (Button)findViewById(R.id.buttonsend);
  162. BtBack = (Button)findViewById(R.id.buttonback);
  163. BtClose = (Button)findViewById(R.id.buttonclose);
  164. }
  165. //单选按钮
  166. @Override
  167. public void onCheckedChanged(RadioGroup group, int checkedId) {
  168. switch (checkedId)
  169. {
  170. case R.id.radioPC:
  171. encodeType = "GBK";
  172. break;
  173. case R.id.radioMobile:
  174. encodeType = "UTF-1";
  175. break;
  176. default:
  177. break;
  178. }
  179. }
  180. /**
  181. * 连接线程
  182. */
  183. class ConnectedThread extends Thread
  184. {
  185. private InputStream inputStream = null;
  186. private long wait;
  187. private Thread thread;
  188. public ConnectedThread()
  189. {
  190. isRecording = false;
  191. this.wait = 50;
  192. thread = new Thread(new ReadRunnable());
  193. }
  194. public void Stop()
  195. {
  196. isRecording = false;
  197. }
  198. public void Start()
  199. {
  200. isRecording = true;
  201. State state = thread.getState();
  202. if(state == State.NEW)
  203. {
  204. thread.start();
  205. }else thread.resume();
  206. }
  207. private class ReadRunnable implements Runnable
  208. {
  209. @Override
  210. public void run() {
  211. while(isRecording)
  212. {
  213. try {
  214. inputStream = MainActivity.bluetoothSocket.getInputStream();
  215. } catch (IOException e) {
  216. Toast.makeText(getApplicationContext(),"创建input流失败",Toast.LENGTH_SHORT).show();
  217. }
  218. int length =20;
  219. byte[] temp = new byte[length];//创建一个byte数组进行获取
  220. if(inputStream != null)
  221. {
  222. try {
  223. int len = inputStream.read(temp,0,length-1);
  224. if(len > 0)
  225. {
  226. byte[] bluetoothbuff = new byte[len];
  227. System.arraycopy(temp,0,bluetoothbuff,0,bluetoothbuff.length);
  228. String readStr = new String(bluetoothbuff,encodeType);
  229. handler.obtainMessage(01,len,-1,readStr).sendToTarget();
  230. }
  231. Thread.sleep(wait);
  232. } catch (IOException e) {
  233. e.printStackTrace();
  234. } catch (InterruptedException e) {
  235. handler.sendEmptyMessage(00);
  236. }
  237. }
  238. }
  239. }
  240. }
  241. }
  242. private class MyHandler extends android.os.Handler
  243. {
  244. @Override
  245. public void dispatchMessage(Message msg) {
  246. switch (msg.what)
  247. {
  248. case 00:
  249. isRecording = false;
  250. EtReceive.setText("");
  251. EtSend.setHint("soclet连接已关闭");
  252. break;
  253. case 01:
  254. String info = (String)msg.obj;
  255. EtReceive.append(info);
  256. break;
  257. default:
  258. break;
  259. }
  260. }
  261. }
  262. }</span>

效果:




可以通过串口助手进行查看信息。

源代码:http://download.csdn.net/detail/csdnhejingzhou/9413145



声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/知新_RL/article/detail/225335
推荐阅读
相关标签
  

闽ICP备14008679号