-
2020-06-01 22:09:24更多相关内容
-
Android Studio蓝牙通信客户端Demo源码BTClient.rar
2021-03-19 19:29:47最新AS可以直接使用 -
AndroidStudio蓝牙通信
2021-12-13 20:53:08openBluetooth蓝牙开启函数4. BlueToothAdapter.java适配器四、运行界面展示五、源码 一、三种近场通信技术的特点 近场通信技术是一种短距离无线通信技术,它允许设备之间进行非接触点对点数据传输和数据交换。近场...文章目录
一、功能需求
进行蓝牙通信的简要设计与开发
二、页面布局设置
1. 中间列表list_item.xml布局
创建layout文件top.xml中,添加文本框,添加文字,设置为居中,修改文字颜色和LinearLayout背景颜色。
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="wrap_content" android:minHeight="50dp" android:padding="8dp"> <TextView android:layout_width="wrap_content" android:layout_height="match_parent" android:id="@+id/blue_name" android:gravity="center_vertical" android:textColor="#000000"/> <TextView android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/blue_info" android:gravity="center_vertical|right" android:textColor="#000000"/> </LinearLayout>
2. activity_main.xml
我想要的效果是页面最上方开启蓝牙,中间显示可连接设备,最下方用于接收消息和发送消息。可以一排两个内容设置一个LinearLayout,其中分别是bottom和text,用来展示信息。
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:background="@drawable/photo" android:padding="20dp"> <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content"> <Button android:id="@+id/btn_openBT" android:layout_width="wrap_content" android:layout_height="wrap_content" android:backgroundTint="@color/colorPrimaryDark" android:text="设置在线"/> <TextView android:id="@+id/text_state2" android:layout_marginLeft="40dp" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textColor="@color/black" android:text="蓝牙已经打开"/> </LinearLayout> <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content"> <Button android:layout_marginTop="10dp" android:id="@+id/btn_search" android:layout_width="wrap_content" android:layout_height="wrap_content" android:backgroundTint="@color/colorPrimaryDark" android:text="我的好友"/> <TextView android:layout_marginTop="10dp" android:id="@+id/text_state" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="40dp" android:textColor="@color/black" /> </LinearLayout> <ListView android:layout_marginTop="10dp" android:id="@+id/listView" android:layout_width="match_parent" android:layout_height="400dp" android:textColor="@color/white" /> <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content"> <Button android:layout_marginTop="10dp" android:id="@+id/btn_receive" android:layout_width="wrap_content" android:layout_height="wrap_content" android:backgroundTint="@color/colorPrimaryDark" android:text="来信"/> <TextView android:id="@+id/text_msg" android:layout_marginTop="10dp" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="20dp" android:textColor="@color/black" android:textColorHint="@color/white" android:text="请你发送消息"/> </LinearLayout> <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content"> <Button android:layout_marginTop="10dp" android:id="@+id/btn_send" android:layout_width="wrap_content" android:layout_height="wrap_content" android:backgroundTint="@color/colorPrimaryDark" android:text="发送"/> <EditText android:id="@+id/text_Edit" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_marginLeft="20dp" android:hint="现在发送的信息是我来选择的" android:textColor="@color/black" android:textColorHint="@color/black" android:textSize="14dp" /> </LinearLayout> </LinearLayout>
三、页面跳转控制(java文件)
1. MainActivity.java
public class MainActivity extends AppCompatActivity implements View.OnClickListener { private BluetoothAdapter bTAdatper; private ListView listView; private BlueToothAdapter adapter; private TextView text_state; private TextView text_msg; private final int BUFFER_SIZE = 1024; private static final String NAME = "BT_DEMO"; private ConnectThread connectThread; private ListenerThread listenerThread; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initView(); bTAdatper = BluetoothAdapter.getDefaultAdapter(); initReceiver(); listenerThread = new ListenerThread(); listenerThread.start(); } private void initView() { findViewById(R.id.btn_openBT).setOnClickListener(this); findViewById(R.id.btn_search).setOnClickListener(this); findViewById(R.id.btn_send).setOnClickListener(this); text_state = (TextView) findViewById(R.id.text_state); text_msg = (TextView) findViewById(R.id.text_msg); listView = (ListView) findViewById(R.id.listView); adapter = new BlueToothDeviceAdapter(getApplicationContext(), R.layout.bluetooth_device_list_item); listView.setAdapter(adapter); listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { if (bTAdatper.isDiscovering()) { bTAdatper.cancelDiscovery(); } BluetoothDevice device = (BluetoothDevice) adapter.getItem(position); connectDevice(device); } }); } private void initReceiver() { //注册广播 IntentFilter filter = new IntentFilter(); filter.addAction(BluetoothDevice.ACTION_FOUND); filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED); filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED); registerReceiver(mReceiver, filter); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.btn_openBT: openBlueTooth(); break; case R.id.btn_search: searchDevices(); break; case R.id.btn_send: if (connectThread != null) { connectThread.sendMsg("这是蓝牙发送过来的消息"); } break; } } @Override protected void onDestroy() { super.onDestroy(); if (bTAdatper != null && bTAdatper.isDiscovering()) { bTAdatper.cancelDiscovery(); } unregisterReceiver(mReceiver); } private final BroadcastReceiver mReceiver = new 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); if (device.getBondState() != BluetoothDevice.BOND_BONDED) { adapter.add(device); adapter.notifyDataSetChanged(); } } else if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) { Toast.makeText(MainActivity.this, "开始搜索", Toast.LENGTH_SHORT).show(); } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) { Toast.makeText(MainActivity.this, "搜索完毕", Toast.LENGTH_SHORT).show(); } } }; public void sendMsg(final String msg) { byte[] bytes = msg.getBytes(); if (outputStream != null) { try { //发送数据 outputStream.write(bytes); text_msg.post(new Runnable() { @Override public void run() { text_msg.setText(getResources().getString(R.string.send_msgs)+msg); } }); } catch (IOException e) { e.printStackTrace(); text_msg.post(new Runnable() { @Override public void run() { text_msg.setText(getResources().getString(R.string.send_msg_error)+msg); } }); } } } }
2. ConnectThread连接线程
连接线程,专门用来对外发出连接对方蓝牙的请求和处理流程。构造函数里通过 BluetoothDevice.createRfcommSocketToServiceRecord() ,从待连接的 device 产生BluetoothSocket. 然后在 run 方法中 connect ,成功后调用BluetoothChatSevice 的connected() 方法。定义 cancel() 在关闭线程时能够关闭相关socket 。
private class ConnectThread extends Thread { private final BluetoothSocket mmSocket; private final BluetoothDevice mmDevice; public ConnectThread(BluetoothDevice device) { mmDevice = device; BluetoothSocket tmp = null; try { tmp = device.createRfcommSocketToServiceRecord(MY_UUID); } catch (IOException e) { e.printStackTrace(); } mmSocket = tmp; } @Override public void run() { setName("ConnectThread"); mAdapter.cancelDiscovery(); try { mmSocket.connect(); } catch (IOException e) { connectionFailed(); try { mmSocket.close(); } catch (IOException e2) { e.printStackTrace(); } ChatService.this.start(); return; } synchronized (ChatService.this) { mConnectThread = null; } connected(mmSocket, mmDevice); } public void cancel() { try { mmSocket.close(); } catch (IOException e) { e.printStackTrace(); } } }
3. openBluetooth蓝牙开启函数
private void openBluetooth() { if (bTAdatper == null) { Toast.makeText(this, Toast.LENGTH_SHORT).show(); } if (!bTAdatper.isEnabled()) { bTAdatper.enable(); } if (bTAdatper.getScanMode() != BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) { Intent i = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE); i.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 0); startActivity(i); } } private void searchDevices() { if (bTAdatper.isDiscovering()) { bTAdatper.cancelDiscovery(); } getBoundedDevices(); bTAdatper.startDiscovery(); }
4. BlueToothAdapter.java适配器
public class BlueToothAdapter extends ArrayAdapter<BluetoothDevice> { private final LayoutInflater mInflater; private int mResource; public BlueToothDeviceAdapter(Context context, int resource) { super(context, resource); mInflater = LayoutInflater.from(context); mResource = resource; } @Override public View getView(int position, View convertView, ViewGroup parent) { if (convertView == null) { convertView = mInflater.inflate(mResource, parent, false); } TextView name = (TextView) convertView.findViewById(R.id.device_name); TextView info = (TextView) convertView.findViewById(R.id.device_info); BluetoothDevice device = getItem(position); name.setText(device.getName()); info.setText(device.getAddress()); return convertView; } }
四、运行界面展示
五、源码
-
androidstudio app连接蓝牙模块进行通信
2018-08-01 11:32:47app连接蓝牙模块2.0进行互相通讯,使用androidstudio编写,页面相对简单,但是功能完善,蓝牙必须先配对再在app中连接 -
Android Studio 蓝牙通信BlueTooth
2020-06-01 21:31:03BlueTooth蓝牙通信作业内容配置蓝牙使用权限页面布局Layout文件夹中Values文件夹中Menu文件夹中事件监听控制服务组件ChatService.javaweixinFragment.java实现界面展示 作业内容 在类微信程序的第一子项中完成“蓝牙...BlueTooth蓝牙通信
作业内容
在类微信程序的第一子项中完成“蓝牙聊天功能”
配置蓝牙使用权限
在AndroidManifest.xml文件里,添加蓝牙使用权限:
<!--下面2个是普通权限,只需要在清单文件里注册,不需要在程序里动态申请--> <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" /> <uses-permission android:name="android.permission.BLUETOOTH" />
页面布局
Layout文件夹中
在页面对应的布局文件里,添加Toolbar控件、ListView控件、EditText控件和Button控件。
<androidx.appcompat.widget.Toolbar android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="wrap_content"> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal"> <TextView android:id="@+id/title_left_text" style="?android:attr/windowTitleStyle" android:layout_width="0dp" android:layout_height="match_parent" android:layout_alignParentLeft="true" android:layout_weight="1" android:gravity="left" android:ellipsize="end" android:singleLine="true" /> <TextView android:id="@+id/title_right_text" android:layout_width="0dp" android:layout_height="match_parent" android:layout_alignParentRight="true" android:layout_weight="1" android:ellipsize="end" android:gravity="right" android:singleLine="true" android:textColor="#fff" /> </LinearLayout> </androidx.appcompat.widget.Toolbar>
device_list.xml文件中,显示“我的好友”以及搜索好友:
<TextView android:id="@+id/title_paired_devices" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="@string/title_paired_devices" android:visibility="gone" android:background="#666" android:textColor="#fff" android:paddingLeft="5dp" /> <ListView android:id="@+id/paired_devices" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_weight="1" /> <TextView android:id="@+id/title_new_devices" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="@string/title_other_devices" android:visibility="gone" android:background="#666" android:textColor="#fff" android:paddingLeft="5dp" /> <!--android:visibility="gone"表示不占空间的隐藏,invisible是占空间--> <ListView android:id="@+id/new_devices" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_weight="2" /> <Button android:id="@+id/button_scan" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="@string/button_scan" />
Values文件夹中
在strings.xml文件里,添加程序运行过程中的状态描述文本等。
<string name="send">发送</string> <string name="not_connected">你没有链接一个设备</string> <string name="bt_not_enabled_leaving">蓝牙不可用,离开聊天室</string> <string name="title_connecting">链接中...</string> <string name="title_connected_to">连接到:</string> <string name="title_not_connected">无链接</string> <string name="scanning">蓝牙设备搜索中...</string> <string name="select_device">选择一个好友链接</string> <string name="none_paired">没有配对好友</string> <string name="none_found">附近没有发现好友</string> <string name="title_paired_devices">已配对好友</string> <string name="title_other_devices">其它可连接好友</string> <string name="button_scan">搜索好友</string> <string name="connect">我的好友</string> <string name="discoverable">设置在线</string> <string name="back">退出</string> <string name="startVideo">开始聊天</string> <string name="stopVideo">结束聊天</string>
Menu文件夹中
<?xml version="1.0" encoding="utf-8"?> <menu xmlns:android="http://schemas.android.com/apk/res/android"> <item android:id="@+id/scan" android:icon="@android:drawable/ic_menu_myplaces" android:title="@string/connect" /> <item android:id="@+id/discoverable" android:icon="@android:drawable/ic_menu_view" android:title="@string/discoverable" /> <item android:id="@+id/back" android:icon="@android:drawable/ic_menu_close_clear_cancel" android:title="@string/back" /> </menu>
事件监听控制
服务组件ChatService.java
三个内部类:AcceptThread(接受新连接)、ConnectThread(发出连接)和ConnectedThread (已连接)
// 创建监听线程,准备接受新连接。使用阻塞方式,调用 BluetoothServerSocket.accept() private class AcceptThread extends Thread { private final BluetoothServerSocket mmServerSocket; public AcceptThread() { BluetoothServerSocket tmp = null; try { //使用射频端口(RF comm)监听 tmp = mAdapter.listenUsingRfcommWithServiceRecord(NAME, MY_UUID); } catch (IOException e) { } mmServerSocket = tmp; } @Override public void run() { setName("AcceptThread"); BluetoothSocket socket = null; while (mState != STATE_CONNECTED) { try { socket = mmServerSocket.accept(); } catch (IOException e) { break; } if (socket != null) { synchronized (ChatService.this) { switch (mState) { case STATE_LISTEN: case STATE_CONNECTING: connected(socket, socket.getRemoteDevice()); break; case STATE_NONE: case STATE_CONNECTED: try { socket.close(); } catch (IOException e) { e.printStackTrace(); } break; } } } } } public void cancel() { try { mmServerSocket.close(); } catch (IOException e) { e.printStackTrace(); } } } /* 连接线程,专门用来对外发出连接对方蓝牙的请求和处理流程。 构造函数里通过 BluetoothDevice.createRfcommSocketToServiceRecord() , 从待连接的 device 产生 BluetoothSocket. 然后在 run 方法中 connect , 成功后调用 BluetoothChatSevice 的 connected() 方法。定义 cancel() 在关闭线程时能够关闭相关socket 。 */ private class ConnectThread extends Thread { private final BluetoothSocket mmSocket; private final BluetoothDevice mmDevice; public ConnectThread(BluetoothDevice device) { mmDevice = device; BluetoothSocket tmp = null; try { tmp = device.createRfcommSocketToServiceRecord(MY_UUID); } catch (IOException e) { e.printStackTrace(); } mmSocket = tmp; } @Override public void run() { setName("ConnectThread"); mAdapter.cancelDiscovery(); try { mmSocket.connect(); } catch (IOException e) { connectionFailed(); try { mmSocket.close(); } catch (IOException e2) { e.printStackTrace(); } ChatService.this.start(); return; } synchronized (ChatService.this) { mConnectThread = null; } connected(mmSocket, mmDevice); } public void cancel() { try { mmSocket.close(); } catch (IOException e) { e.printStackTrace(); } } } /* 双方蓝牙连接后一直运行的线程;构造函数中设置输入输出流。 run()方法中使用阻塞模式的 InputStream.read()循环读取输入流,然后发送到 UI 线程中更新聊天消息。 本线程也提供了 write() 将聊天消息写入输出流传输至对方,传输成功后回写入 UI 线程。最后使用cancel()关闭连接的 socket */ private class ConnectedThread extends Thread { private final BluetoothSocket mmSocket; private final InputStream mmInStream; private final OutputStream mmOutStream; public ConnectedThread(BluetoothSocket socket) { mmSocket = socket; InputStream tmpIn = null; OutputStream tmpOut = null; try { tmpIn = socket.getInputStream(); tmpOut = socket.getOutputStream(); } catch (IOException e) { e.printStackTrace(); } mmInStream = tmpIn; mmOutStream = tmpOut; } @Override public void run() { byte[] buffer = new byte[1024]; int bytes; while (true) { try { bytes = mmInStream.read(buffer); mHandler.obtainMessage(weixinFragment.MESSAGE_READ, bytes, -1, buffer).sendToTarget(); } catch (IOException e) { connectionLost(); break; } } } public void write(byte[] buffer) { try { mmOutStream.write(buffer); mHandler.obtainMessage(weixinFragment.MESSAGE_WRITE, -1, -1, buffer).sendToTarget(); } catch (IOException e) { e.printStackTrace(); } } public void cancel() { try { mmSocket.close(); } catch (IOException e) { e.printStackTrace(); } } }
weixinFragment.java
创建选项菜单-选项菜单监听-得到本地蓝牙适配器
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment view= inflater.inflate(R.layout.tab01, container, false); Toolbar toolbar = view.findViewById(R.id.toolbar); setHasOptionsMenu(true); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { if (ContextCompat.checkSelfPermission(this.getContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(getActivity(),new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 1); } } toolbar.inflateMenu(R.menu.option_menu); toolbar.setOnMenuItemClickListener(new MyMenuItemClickListener()); mTitle = view.findViewById(R.id.title_left_text); mTitle.setText(R.string.app_name); mTitle = view.findViewById(R.id.title_right_text); mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); if (mBluetoothAdapter == null) { Toast.makeText(view.getContext(), "蓝牙不可用", Toast.LENGTH_LONG).show(); getActivity().finish(); return view; } if (!mBluetoothAdapter.isEnabled()) { //若当前设备蓝牙功能未开启 Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(enableIntent, REQUEST_ENABLE_BT); // } else { if (mChatService == null) { setupChat(); //创建会话 } } return view; }
实现界面展示
模拟器蓝牙不可用。因身边无安卓系统手机,于是无法安装到手机上运行。
附上源码: 蓝牙通信BlueTooth(Gitee).
-
android studio——蓝牙通信
2021-12-13 17:32:24文章目录一、结果展示二、核心代码1、AndroidManifest.xml文件2、MainActivity.java文件3、activity.xml文件 一、结果展示 点击“打开手机蓝牙”: ...uses-permission android:name="android.permission.BLUE一、结果展示
点击“打开手机蓝牙”:
点击“允许检测”:
已配对成功:
点击关闭蓝牙:
二、核心代码
1、AndroidManifest.xml文件
在AndroidManifest.xml文件中添加如下代码来申请权限
第一行为发现其他设备<uses-permission android:name="android.permission.BLUETOOTH"/> <uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
2、MainActivity.java文件
package com.example.bluetooth; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import java.util.ArrayList; import java.util.Set; public class MainActivity extends AppCompatActivity { //蓝牙适配器 private BluetoothAdapter mBluetoothAdapter; //用来存放搜到的蓝牙 private Set<BluetoothDevice> mDevices; private ListView mListView; private ArrayList mList; private ArrayAdapter mAdapter; private TextView mConnectedView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //自定义方法初始化UI控件 initView(); initData(); } private void initData() { //实例化蓝牙适配器 mBluetoothAdapter =BluetoothAdapter.getDefaultAdapter(); } private void initView() { // mListView = (ListView) findViewById(R.id.lv_bluetooth_name); // mConnectedView 指的是已被连接的(可用的蓝牙) mConnectedView = (TextView) findViewById(R.id.tv_bluetooth_connected); } public void onClick(View view) { if (view != null) { switch (view.getId()){ /** * 选择打开开启蓝牙。但是当选择它,蓝牙将不会被打开。 * 事实上它会询问许可,以启用蓝牙。 */ case R.id.bt_bluetooth_on: /** * 判断BluetoothAdapter 是否已经在准备状态,没有的话,就打开 */ if (!mBluetoothAdapter.isEnabled()) { //调用下列蓝牙ACTION_REQUEST_ENABLE的意图 Intent turnOn =new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(turnOn,0); Toast.makeText(MainActivity.this, "turn on", Toast.LENGTH_LONG).show(); }else{ Toast.makeText(MainActivity.this, "Already on", Toast.LENGTH_LONG).show(); } break; /** * 开启许可,允许其他蓝牙设备120秒内可以搜索到该设备 * 选择设置可见按钮来打开视图。 * 下面的屏幕会出现要求许可才能打开发现120秒 */ case R.id.bt_bluetooth_visible: if (mBluetoothAdapter.isEnabled()) { Intent getVisible = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE); startActivityForResult(getVisible,0); }else{ Toast.makeText(MainActivity.this, "请先开启蓝牙", Toast.LENGTH_SHORT).show(); } break; /** * 选择列表中的设备选项。它会列出倒在列表视图中的配对设备。 * 就我而言,只有一个配对设备。它如下所示。 */ case R.id.bt_bluetooth_list: //可以通过调用 getBondedDevices()方法来获取配对设备列表 mDevices = mBluetoothAdapter.getBondedDevices(); //在这初始化ListView是为了方便刷新,显示数据 mListView = (ListView) findViewById(R.id.lv_bluetooth_name); mList = new ArrayList(); if (mBluetoothAdapter.isEnabled()) { for (BluetoothDevice bd :mDevices){ mList.add(bd.getName()); } if (mList.size() != 0){ mConnectedView.setVisibility(View.VISIBLE); } Toast.makeText(MainActivity.this, "Showing Paired Devices", Toast.LENGTH_SHORT).show(); mAdapter = new ArrayAdapter( this,android.R.layout.simple_list_item_1,mList); mListView.setAdapter(mAdapter); mAdapter.notifyDataSetChanged(); }else{ Toast.makeText(MainActivity.this, "请先开启蓝牙", Toast.LENGTH_SHORT).show(); } break; /** * 选择关闭按钮来关闭蓝牙。 * 当关掉蓝牙指示成功切换关闭蓝牙会出现以下消息 */ case R.id.bt_bluetooth_off: //判断蓝牙是否关闭 if (mBluetoothAdapter.isEnabled()){ //未关闭 mBluetoothAdapter.disable(); mList.clear(); mConnectedView.setVisibility(View.INVISIBLE); mAdapter.notifyDataSetChanged(); } Toast.makeText(getApplicationContext(),"蓝牙已关闭" , Toast.LENGTH_LONG).show(); break; default: break; } } } }
3、activity.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:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".MainActivity"> <ScrollView android:id="@+id/scv_bluetooth_view" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:layout_alignParentLeft="true" android:layout_alignParentRight="true" android:layout_alignParentTop="true"/> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <TextView android:id="@+id/tv_bluetooth_view" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/app_name" android:textAppearance="?android:attr/textAppearanceLarge"/> <Button android:id="@+id/bt_bluetooth_on" android:layout_width="wrap_content" android:layout_height="wrap_content" android:onClick="onClick" android:text="打开手机蓝牙"/> <Button android:id="@+id/bt_bluetooth_visible" android:layout_width="wrap_content" android:layout_height="wrap_content" android:onClick="onClick" android:text="允许检测性"/> <Button android:id="@+id/bt_bluetooth_list" android:layout_width="wrap_content" android:layout_height="wrap_content" android:onClick="onClick" android:text="打开已配对列表"/> <Button android:id="@+id/bt_bluetooth_off" android:layout_width="wrap_content" android:layout_height="wrap_content" android:onClick="onClick" android:text="关闭蓝牙"/> <TextView android:visibility="invisible" android:id="@+id/tv_bluetooth_connected" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="已配对设备"/> <ListView android:id="@+id/lv_bluetooth_name" android:layout_width="match_parent" android:layout_height="wrap_content"/> <LinearLayout android:visibility="invisible" android:id="@+id/ll_bluetooth_layout" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal"> <TextView android:id="@+id/tv_bluetooth_usable" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="可用设备"/> <TextView android:id="@+id/tv_bluetooth_touch" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="触摸可配对"/> </LinearLayout> </LinearLayout> </RelativeLayout>
源码已上传至GitHub
-
Android Studio 最新蓝牙服务端源码 蓝牙通信代码BluetoothService.rar
2021-03-19 19:28:28根据最新的AS整理,下载可直接运行,一些坑已经写好了 -
基于Android Studio的蓝牙通信的简单应用与开发
2021-12-13 15:13:11实现基于Android Studio的蓝牙通信的简单应用与开发实现蓝牙通信界面展示核心文件部分代码展示总结 实现蓝牙通信 通过权限申请与代码实现,完成蓝牙通信的简单应用与开发。 界面展示 核心文件 三个主要核心java文件... -
android studio实现蓝牙通信
2020-06-01 19:19:39目录添加蓝牙权限在文件res/values/strings.xml里,添加程序运行过程中的状态描述文本编写布局文件添加一个编写用于蓝牙会话的服务组件ChatService建立供BluetoothChat使用的菜单文件optionmenu.xml新建组件Device... -
Android Studio开发之蓝牙通信
2020-06-01 20:53:55安卓开发-蓝牙通信 功能需求:在微信程序的第一子项中完成“蓝牙聊天功能” 开发步骤: 配置文件注册 设计界面布局 编写用于蓝牙会话的服务组件ChatService 分别建立供主Activity使用的菜单文件res/menu/optionmenu... -
android_studio手机蓝牙串口通信源代码
2017-11-29 09:25:11android_studio手机蓝牙串口通信源代码,我自己已经下载到手机上调试过,可以用。讲解清楚,十分受用! -
Android Studio 简要实现蓝牙(Bluetooth)通信(附加作业)
2021-12-13 14:34:42简要实现设备蓝牙通信2.模拟Client 和Server端实现简单的通信。三、实验项目截图四、源代码 一、项目实现功能 1.两台设备可以通过蓝牙进行通信 2.模拟Client 和Server端实现简单的通信。 二、项目核心代码 1.简要... -
基于android studio的蓝牙模块
2018-01-10 22:04:42基于Android studio的蓝牙开发代码,正在进行android程序开发的小伙伴可以看一下,可用于手环二次开发的蓝牙模块的书写。 -
## Android Studio 开发(四)--蓝牙通信
2021-12-11 17:16:51Android Studio 开发(三)–百度地图定位APP ...进行蓝牙通信的简要设计与开发。 二、关键步骤 1、工程结构 新建相应的活动组件、布局文件、准备好相应资源,确定整体架构。 (主活动组件MainActivity被重命名为Blu -
Android Studio 用手机蓝牙连接单片机并显示波形
2021-12-03 10:46:51点击“连接”按钮与周围的蓝牙设备进行配对,自动接收规定格式的信号,并显示对应的波形图、峰峰值、频率、THDx、五次谐波的归一化幅值 说明链接:https://blog.csdn.net/qq_39542170/article/details/121691497 -
蓝牙通信 Android APP源码
2020-10-22 19:05:54这是一份蓝牙通信 Android APP源码,采用Android Studio开发,代码风格良好,使用蜂汇物联科技的BLE模块测试过。 -
Android Phone蓝牙通信方式总结(Socket与Gatt)
2021-01-03 16:50:18Android手机间通过蓝牙方式进行通信,有两种常见的...其实无论是socket方式还是Gatt,Android设备间蓝牙通信都是一种CS(client-server)模式。 1)socket服务端: 使用listenUsingInsecureRfcommWithServiceRecord接口 -
Android studio 蓝牙通讯
2020-06-01 15:47:52搜索附近的蓝牙设备 与指定设备连接 连接成功后可以互发消息 结果截图 项目源码 GitHub:点此跳转 核心代码 开启一个 ConnectedThread 来管理对应的当前连接。之前先取消任意现存的 mConnectThread 、... -
android studio蓝牙基本功能
2015-12-28 11:28:49完成两台手机的蓝牙数据传输功能,一台作为服务器,一台作为客户端,注意UUID得改一下,每台手机的UUID都不一样,可以在线调试代码查看当前手机的UUID -
android studio 蓝牙 socket 范例
2015-10-21 02:18:36这是很简洁的android 蓝牙和socket的范例,开发环境为android studio -
Android Studio实现蓝牙聊天通讯
2020-05-31 21:57:51Android Studio实现蓝牙聊天通讯我的项目项目源码程序截图开发流程创建项目通信原理Android Studio近距离通信:Bluetooth蓝牙工作流程蓝牙通信API代码阶段蓝牙通信添加权限查找设备获取查找结果设备绑定官方文档参考... -
Android 蓝牙通信简单实例
2017-09-19 19:57:14这是一个Android蓝牙开发的小程序,代码简单,实现了蓝牙打开、搜索、配对、连接、通信等功能。两个Android项目,一个服务器一个客户端 -
Android studio BLE通信助手(工程文件+apk)
2017-04-10 07:36:56该工程文件可直接修改 未做服务特征自动扫描 可用于蓝牙模块GDY-8和GDY-10,其他自行尝试 -
蓝牙串口助手(Android Studio源码)
2021-01-12 14:33:06本软件为蓝牙串口通信工具,支持蓝牙从模式和主模式,可进行蓝牙串口通信测试。能连接单片机及PC的蓝牙串口。 可用于硬件的串口蓝牙模块(TTL)通信。 软件功能: 1、搜索蓝牙设备 2、接收显示数据与发送数据 3、可...