时间:2021-05-20
本文实例为大家分享了android实现手机与单片机蓝牙模块通信的具体代码,供大家参考,具体内容如下
我是参考原博客的内容去写的,由于原博客写的不全,少了关键的几个类,然后我就凭借自己扎实的功底补出来了,现在蓝牙工作正常,能发能收!在看这边文章之前你要先了解一下蓝牙的工作状态,我的代码里面可能解释的不是很详细,但是我自己是能看懂的!
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");//没有用到 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();//停止搜索 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(); } } }); } /** *开启蓝牙且被发现 */ private void enablebluetooth(){ mBtAdapter=BluetoothAdapter.getDefaultAdapter(); /** *if(!mBtAdapter.isEnabled()){这里可以先使能,可以在REQUEST_DISCOVERABLE处使能,这样的话可以连使能和请求被发现一块完成 // mBtAdapter.enable(); Intent enableIntent=new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(enableIntent,REQUEST_ENABLE); } else { show("蓝牙已开启"); }*/ Intent enable = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE); enable.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300); startActivityForResult(enable, REQUEST_DISCOVERABLE); } /** * 销毁事件,注销广播 */ @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("连接失败"); try { client.connect(); } catch (Exception e) { Log.e("TAG", e.toString()); } break; case BlueToothTool.CONNECT_SUCCESS: show("连接成功"); mListView.setVisibility(View.INVISIBLE); break; case BlueToothTool.READ_FAILED: show("读取失败"); break; case BlueToothTool.WRITE_FAILED: show("写入失败"); break; case BlueToothTool.DATA: mstringbuilder.append(msg.obj.toString()); show(mstringbuilder.toString()); break; } } }; /** * 请求响应结果 * @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("蓝牙未开启"); } else show("蓝牙已开启"); break;*/ case REQUEST_DISCOVERABLE: if(resultCode==Activity.RESULT_CANCELED){ show("蓝牙未开启"); } else show("蓝牙已开启"); 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; /** * 注册广播事件 */ @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); } /** * 广播 */ 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)// 防止重复添加 ListDevice.add(str); // 获取设备名称和mac地址 if (mAdapter != null) { mAdapter.notifyDataSetChanged(); } showDevices(); } else if(BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)){ progressBar.setVisibility(View.INVISIBLE); show("已停止寻找"); } } }; /** * 菜单栏点击事件 * @param item * @return */ @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()){ case R.id.search: if(!mBtAdapter.isEnabled()){ show("蓝牙未开启"); } else { mBtAdapter.startDiscovery(); show("正在寻找设备"); progressBar.setVisibility(View.VISIBLE); } break; case R.id.about: Toast.makeText(MainActivity.this,"关于我们",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); } /** * 更新UI方法 * @param string */ private void show(final String string){ runOnUiThread(new Runnable() { @Override public void run() { status.setText(string); } }); } }然后我的读任务和写任务以及连接任务是在另一个类里面实现的,也就是BlueToothTool类,这个类一个原博客是没有写的,只是MainActivity中用到了这个类的一些方法,但是没有给出,所以就让一些同学很蛋疼。我看完之后是自己补全的这个类!
以上就是我的蓝牙与单片机连接通信的全过程,顺便说一下,这个连接是自动连接的,不需要什么秘钥什么的,直接搜索到HC-05蓝牙直接就可以确定连接,亲测有效。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。
适用于msp430g2553单片机使用到了hc-sr04超声测距模块,使用UART与PC通信。复制代码代码如下:#includelongcurrent_time
引言我有一个显示屏模块:模块上有一个128*64的单色显示屏,一个单片机(B)控制它显示的内容。单片机的I²C总线通过四边上的排针排母连接到其他单片机
单片机与plc的区别体现在性能和使用范围方面。PLC是应用单片机构成的比较成熟的控制系统,是已经调试成熟稳定的单片机应用系统的产品。有较强的通用性。而单片机可以
stm32是将单片机所能实现某些功能的元器件焊接在电路板上,目的是便于单片机爱好者。单片机是典型的嵌入式微控制器(MicrocontrollerUnit),由运
Android与单片机通信常用数据转换方法 1.将GB2312转化为中文,如BAFAC2DCB2B7→胡萝卜,两个字节合成一个文字publicstaticSt