Realization of Communication between Mobile Phone and MCU Bluetooth Module by android
- 2021-09-11 21:10:31
- OfStack
In this paper, we share the specific code of android to realize the communication between mobile phone and MCU Bluetooth module for your reference. The specific contents are as follows
I am referring to the original blog content to write, because the original blog is not complete, missing a few key classes, and then I rely on their solid foundation to make up, Bluetooth now works normally, can send can receive! Before reading this article, you should first understand the working state of Bluetooth. My code may not explain it in detail, but I can understand it myself!
package com.example.fsl.bluetooth;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
public class MainActivity extends AppCompatActivity {
private Toolbar toolbar;
private TextView status;
private StringBuilder mstringbuilder;
private static final UUID MY_UUID=UUID.fromString("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) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar=(Toolbar)findViewById(R.id.toolbar);
status=(TextView)findViewById(R.id.textView2);
mListView=(ListView)findViewById(R.id.listView);
mbutton=(Button)findViewById(R.id.button);
editText=(EditText)findViewById(R.id.editText);
progressBar=(ProgressBar)findViewById(R.id.progressBar);
progressBar.setVisibility(View.INVISIBLE);
loopProgressBar=(LoopProgressBar)findViewById(R.id.loop);
ListDevice=new ArrayList<String>();
mstringbuilder=new StringBuilder();
setSupportActionBar(toolbar);
enablebluetooth();
mbutton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
BlueToothTool.WriteTask W=client.new WriteTask(editText.getText().toString());
W.start();
}
});
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
mBtAdapter.cancelDiscovery();// Stop the search
progressBar.setVisibility(View.INVISIBLE);
String str = ListDevice.get(position);
String macAdress = str.split("\\|")[1];
BluetoothDevice device = mBtAdapter.getRemoteDevice(macAdress);
client=new BlueToothTool(device,handler);
try{
client.connect();
}catch (Exception e){
e.printStackTrace();
}
}
});
}
/**
* Turn on Bluetooth and be found
*/
private void enablebluetooth(){
mBtAdapter=BluetoothAdapter.getDefaultAdapter();
/**
*if(!mBtAdapter.isEnabled()){ You can enable it here first, and you can use it in REQUEST_DISCOVERABLE Enable at, so that both the enable and the request can be found 1 Block completion
// mBtAdapter.enable();
Intent enableIntent=new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableIntent,REQUEST_ENABLE);
}
else {
show(" Bluetooth is on ");
}*/
Intent enable = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
enable.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
startActivityForResult(enable, REQUEST_DISCOVERABLE);
}
/**
* Destroy events, cancel broadcasts
*/
@Override
protected void onDestroy() {
unregisterReceiver(receiver);
super.onDestroy();
}
private final Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case BlueToothTool.CONNECT_FAILED:
show(" Connection failed ");
try {
client.connect();
} catch (Exception e) {
Log.e("TAG", e.toString());
}
break;
case BlueToothTool.CONNECT_SUCCESS:
show(" Connection succeeded ");
mListView.setVisibility(View.INVISIBLE);
break;
case BlueToothTool.READ_FAILED:
show(" Read failed ");
break;
case BlueToothTool.WRITE_FAILED:
show(" Write failure ");
break;
case BlueToothTool.DATA:
mstringbuilder.append(msg.obj.toString());
show(mstringbuilder.toString());
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 is not turned on ");
}
else
show(" Bluetooth is on ");
break;*/
case REQUEST_DISCOVERABLE:
if(resultCode==Activity.RESULT_CANCELED){
show(" Bluetooth is not turned on ");
}
else
show(" Bluetooth is on ");
break;
default:
break;
}
}
public boolean onCreateOptionsMenu(Menu menu){
getMenuInflater().inflate(R.menu.menu,menu);
return true;
}
private static final int REQUEST_ENABLE=1;
private static final int REQUEST_DISCOVERABLE=2;
/**
* Register Broadcast Events
*/
@Override
public void onResume(){
super.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 = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
String str = device.getName() + "|" + device.getAddress();
if (ListDevice.indexOf(str) == -1)// Prevent repeated additions
ListDevice.add(str); // Gets the device name and mac Address
if (mAdapter != null) {
mAdapter.notifyDataSetChanged();
}
showDevices();
}
else if(BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)){
progressBar.setVisibility(View.INVISIBLE);
show(" The search has been stopped ");
}
}
};
/**
* Menu bar click event
* @param item
* @return
*/
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.search:
if(!mBtAdapter.isEnabled()){
show(" Bluetooth is not turned on ");
}
else {
mBtAdapter.startDiscovery();
show(" Looking for equipment ");
progressBar.setVisibility(View.VISIBLE);
}
break;
case R.id.about:
Toast.makeText(MainActivity.this," About us ",Toast.LENGTH_SHORT).show();
break;
default:
}
return true;
}
private void showDevices() {
mAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,
ListDevice);
mListView.setAdapter(mAdapter);
}
/**
* Update UI Method
* @param string
*/
private void show(final String string){
runOnUiThread(new Runnable() {
@Override
public void run() {
status.setText(string);
}
});
}
}
Then my reading task and writing task and connection task are implemented in another class, that is, BlueToothTool class. This class is not written in an original blog, but MainActivity uses some methods of this class, but it is not given, so it makes some students very painful. After I read it, I completed this class by myself!
package com.example.fsl.bluetooth;
import android.app.Notification;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.util.logging.LogRecord;
/**
* 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){
this.device=device;
this.mhandler=handler;
}
/**
* Open up connection thread task
*/
public void connect(){
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
BluetoothSocket tmp = null;
Method method;
try {
method = device.getClass().getMethod("createRfcommSocket", new Class[]{int.class});
tmp = (BluetoothSocket) method.invoke(device, 1);
} catch (Exception e) {
setState(CONNECT_FAILED);
Log.e("TAG", e.toString());
}
socket = tmp;
try {
socket.connect();
isConnect = true;
setState(CONNECT_SUCCESS);
Readtask readtask = new Readtask(); // Open the thread to read data after successful connection
readtask.start();
} catch (Exception e) {
setState(CONNECT_FAILED);
Log.e("TAG", e.toString());
}
}
});
new Thread(thread).start();
}
/**
* Open up thread read task
*/
public class Readtask extends Thread{
@Override
public void run(){
byte[] buffer = new byte[1024];
int bytes;
InputStream inputStream ; // Create an input stream to read data
while (true) {
try {
inputStream = socket.getInputStream();
if ((bytes = inputStream.read(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 = mhandler.obtainMessage();
msg.what = DATA;
msg.obj = s;
mhandler.sendMessage(msg);
}
} catch (IOException e) {
setState(READ_FAILED);
Log.e("TAG", e.toString());
break;
}
}
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
Log.e("TAG", e.toString());
}
}
}
}
/**
* Open up thread writing tasks
*/
public class WriteTask extends Thread{
private String srt;
public WriteTask(String str){
this.srt=str;
}
@Override
public void run(){
OutputStream outputStream=null;
byte[] st=srt.getBytes();
try{
outputStream=socket.getOutputStream();
outputStream.write(st);
}catch (Exception e){
setState(WRITE_FAILED);
e.printStackTrace();
}
}
}
private void setState(int mes){
Message message=new Message();
message.what=mes;
mhandler.sendMessage(message);
}
/**
* The following method is not used at present
*/
private byte[] getHexBytes(String message) {
int len = message.length() / 2;
char[] chars = message.toCharArray();
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) Integer.parseInt(hexStr[j], 16);
}
return bytes;
}
}
The above is the whole process of communication between my Bluetooth and MCU. By the way, this connection is automatically connected, and it doesn't need any secret key. If you search HC-05 Bluetooth directly, you can determine the connection, and the pro-test is effective.