This article shares the specific code for Android to realize the communication between mobile phone and microcontroller Bluetooth module for your reference. The specific content is as follows
I wrote it with reference to the content of the original blog. Because the original blog was not fully written, I lacked a few key categories. Then I made up for it with my solid foundation. Now Bluetooth works normally and can be sent or collected! Before reading this article, you should first understand the working status of Bluetooth. My code may not be explained in detail, but I can understand it myself!
package ; import ; import ; import ; import ; import ; import ; import ; import ; import ; import ; import .; import ; import .; import ; import ; import ; import ; import ; import ; import ; import ; import ; import ; import ; import ; import ; import ; import ; public class MainActivity extends AppCompatActivity { private Toolbar toolbar; private TextView status; private StringBuilder mstringbuilder; private static final UUID MY_UUID=("00001101-0000-1000-8000-00805F9B34FB");//Not used BluetoothReceiver receiver; BluetoothAdapter mBtAdapter; BluetoothSocket mBtSocket; private BlueToothTool client; private ListView mListView; private List<String> ListDevice; private ArrayAdapter<String> mAdapter; private Button mbutton; private EditText editText; private ProgressBar progressBar; private LoopProgressBar loopProgressBar; @Override protected void onCreate(Bundle savedInstanceState) { (savedInstanceState); setContentView(.activity_main); toolbar=(Toolbar)findViewById(); status=(TextView)findViewById(.textView2); mListView=(ListView)findViewById(); mbutton=(Button)findViewById(); editText=(EditText)findViewById(); progressBar=(ProgressBar)findViewById(); (); loopProgressBar=(LoopProgressBar)findViewById(); ListDevice=new ArrayList<String>(); mstringbuilder=new StringBuilder(); setSupportActionBar(toolbar); enablebluetooth(); (new () { @Override public void onClick(View v) { W= WriteTask(().toString()); (); } }); (new () { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { ();//Stop search (); String str = (position); String macAdress = ("\\|")[1]; BluetoothDevice device = (macAdress); client=new BlueToothTool(device,handler); try{ (); }catch (Exception e){ (); } } }); } /** *Bluetooth turned on and found */ private void enablebluetooth(){ mBtAdapter=(); /** *if(!()){This can be enabled first, and it can be enabled at REQUEST_DISCOVERABLE, so that the enable and request can be completed together. // (); Intent enableIntent=new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(enableIntent,REQUEST_ENABLE); } else { show("Bluetooth is turned on"); }*/ Intent enable = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE); (BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300); startActivityForResult(enable, REQUEST_DISCOVERABLE); } /** * Destruction incident, cancel the broadcast */ @Override protected void onDestroy() { unregisterReceiver(receiver); (); } private final Handler handler = new Handler() { @Override public void handleMessage(Message msg) { switch () { case BlueToothTool.CONNECT_FAILED: show("Connection failed"); try { (); } catch (Exception e) { ("TAG", ()); } break; case BlueToothTool.CONNECT_SUCCESS: show("Connected successfully"); (); break; case BlueToothTool.READ_FAILED: show("Read failed"); break; case BlueToothTool.WRITE_FAILED: show("Write failed"); break; case : (()); show(()); break; } } }; /** * Request response result * @param requestCode * @param resultCode * @param data */ @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { switch (requestCode){ /** *case REQUEST_ENABLE: if(requestCode!= Activity.RESULT_OK){ show("Bluetooth not turned on"); } else show("Bluetooth is turned on"); break;*/ case REQUEST_DISCOVERABLE: if(resultCode==Activity.RESULT_CANCELED){ show("Bluetooth not turned on"); } else show("Bluetooth is on"); break; default: break; } } public boolean onCreateOptionsMenu(Menu menu){ getMenuInflater().inflate(,menu); return true; } private static final int REQUEST_ENABLE=1; private static final int REQUEST_DISCOVERABLE=2; /** * Register a broadcast event */ @Override public void onResume(){ (); IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND); receiver = new BluetoothReceiver(); registerReceiver(receiver, filter); filter=new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED); registerReceiver(receiver,filter); } /** * Broadcast */ private class BluetoothReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { String action = (); if (BluetoothDevice.ACTION_FOUND.equals(action)) { BluetoothDevice device = (BluetoothDevice.EXTRA_DEVICE); String str = () + "|" + (); if ((str) == -1)// Prevent repeated additions (str); // Get the device name and mac address if (mAdapter != null) { (); } showDevices(); } else if(BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)){ (); show("Stopped searching"); } } }; /** * Menu bar click event * @param item * @return */ @Override public boolean onOptionsItemSelected(MenuItem item) { switch (()){ case : if(!()){ show("Bluetooth not turned on"); } else { (); show("Looking for equipment"); (); } break; case : (,"about Us",Toast.LENGTH_SHORT).show(); break; default: } return true; } private void showDevices() { mAdapter = new ArrayAdapter<String>(this, .simple_list_item_1, ListDevice); (mAdapter); } /** * Update UI method * @param string */ private void show(final String string){ runOnUiThread(new Runnable() { @Override public void run() { (string); } }); } }
Then my reading tasks, writing tasks and connecting tasks are implemented in another class, that is, the BlueToothTool class. This class was not written in the original blog, but some methods of this class were used in MainActivity, but they were not given, so it made some students very upset. After reading this, I completed this category myself!
package ; import ; import ; import ; import ; import ; import ; import .; import ; import ; import ; import ; import ; import ; /** * Created by Fsl on 2017/12/22. */ public class BlueToothTool { private BluetoothDevice device; private Handler mhandler; BluetoothSocket socket; static final int CONNECT_FAILED=1; static final int CONNECT_SUCCESS=5; static final int READ_FAILED=2; static final int WRITE_FAILED=3; static final int DATA=4; private boolean isConnect=false; public BlueToothTool(BluetoothDevice device,Handler handler){ =device; =handler; } /** *Distribute connection thread tasks */ public void connect(){ Thread thread = new Thread(new Runnable() { @Override public void run() { BluetoothSocket tmp = null; Method method; try { method = ().getMethod("createRfcommSocket", new Class[]{}); tmp = (BluetoothSocket) (device, 1); } catch (Exception e) { setState(CONNECT_FAILED); ("TAG", ()); } socket = tmp; try { (); isConnect = true; setState(CONNECT_SUCCESS); Readtask readtask = new Readtask(); //Open the thread to read data after the connection is successful (); } catch (Exception e) { setState(CONNECT_FAILED); ("TAG", ()); } } }); new Thread(thread).start(); } /** *Develop thread reading tasks */ public class Readtask extends Thread{ @Override public void run(){ byte[] buffer = new byte[1024]; int bytes; InputStream inputStream ; //Create input stream to read data while (true) { try { inputStream = (); if ((bytes = (buffer)) > 0) { byte[] buf_data= new byte[bytes]; for (int i = 0; i < bytes; i++) { buf_data[i] = buffer[i]; } String s = new String(buf_data); Message msg = (); = DATA; = s; (msg); } } catch (IOException e) { setState(READ_FAILED); ("TAG", ()); break; } } if (socket != null) { try { (); } catch (IOException e) { ("TAG", ()); } } } } /** *Develop thread writing tasks */ public class WriteTask extends Thread{ private String srt; public WriteTask(String str){ =str; } @Override public void run(){ OutputStream outputStream=null; byte[] st=(); try{ outputStream=(); (st); }catch (Exception e){ setState(WRITE_FAILED); (); } } } private void setState(int mes){ Message message=new Message(); =mes; (message); } /** *The following method has not been used yet */ private byte[] getHexBytes(String message) { int len = () / 2; char[] chars = (); String[] hexStr = new String[len]; byte[] bytes = new byte[len]; for (int i = 0, j = 0; j < len; i += 2, j++) { hexStr[j] = "" + chars[i] + chars[i + 1]; bytes[j] = (byte) (hexStr[j], 16); } return bytes; } }
The above is the entire process of connecting and communicating with my Bluetooth and microcontroller. By the way, this connection is automatically connected and does not require any secret keys or anything. You can directly search for HC-05 Bluetooth to confirm the connection, and it is valid for personal testing.
The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.