精华内容
下载资源
问答
  • 2019-06-19 21:33:14

    代码片段

    activity

    package com.example.day10_2;
    
    import android.Manifest;
    import android.annotation.SuppressLint;
    import android.bluetooth.BluetoothAdapter;
    import android.bluetooth.BluetoothDevice;
    import android.bluetooth.BluetoothManager;
    import android.content.BroadcastReceiver;
    import android.content.Context;
    import android.content.Intent;
    import android.content.IntentFilter;
    import android.content.pm.PackageManager;
    import android.os.Build;
    import android.os.Parcelable;
    import android.support.annotation.NonNull;
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.util.Log;
    import android.view.View;
    import android.widget.AdapterView;
    import android.widget.Button;
    import android.widget.ListView;
    
    import com.example.day10.R;
    
    import java.lang.reflect.InvocationTargetException;
    import java.lang.reflect.Method;
    import java.util.ArrayList;
    import java.util.List;
    
    public class Main2Activity extends AppCompatActivity implements View.OnClickListener {
        List<BluetoothDevice> list;
        MyAdapter myAdapter;
        BluetoothAdapter bluetoothAdapter;
        BluetoothManager bluetoothManager;
        BluetoothReceiver bluetoothReceiver;
    
        Button start, stop, search;
        ListView lv;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main2);
    
            initView();
            request();
            initDate();
        }
    
        public void initDate() {
            bluetoothManager = (BluetoothManager) getSystemService(BLUETOOTH_SERVICE);
            bluetoothAdapter = bluetoothManager.getAdapter();
            if (bluetoothAdapter == null) {
                finish();
                return;
            }
            bluetoothReceiver = new BluetoothReceiver();
            IntentFilter intentFilter = new IntentFilter();
            intentFilter.addAction(BluetoothDevice.ACTION_FOUND);
            intentFilter.addAction(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
            intentFilter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
            registerReceiver(bluetoothReceiver, intentFilter);
        }
    
        public void initView() {
            start = findViewById(R.id.start);
            stop = findViewById(R.id.stop);
            search = findViewById(R.id.serach);
            lv = findViewById(R.id.list);
            list = new ArrayList<>();
    
            start.setOnClickListener(this);
            stop.setOnClickListener(this);
            search.setOnClickListener(this);
    
            myAdapter = new MyAdapter(list);
            lv.setAdapter(myAdapter);
    
            lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    try {
                        Method method = BluetoothDevice.class.getMethod("createBond");
                        method.invoke(list.get(position));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
        }
    
        public void request() {
            if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M) {
                int i = checkSelfPermission(Manifest.permission.BLUETOOTH);
                int i2 = checkSelfPermission(Manifest.permission.BLUETOOTH_ADMIN);
                int i3 = checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION);
    
                int granted = PackageManager.PERMISSION_GRANTED;
                if (i != granted || i2 != granted || granted != i3) {
                    String[] permiss = {Manifest.permission.BLUETOOTH, Manifest.permission.BLUETOOTH_ADMIN, Manifest.permission.ACCESS_COARSE_LOCATION};
                    requestPermissions(permiss, 100);
                }
            }
        }
    
        @Override
        public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
            super.onRequestPermissionsResult(requestCode, permissions, grantResults);
            if (requestCode == 100) {
                if (grantResults[0] != PackageManager.PERMISSION_GRANTED) {
    
                }
            }
        }
    
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.start:
                    boolean enable = bluetoothAdapter.enable();
                    if (!enable) {
                        Intent intent = new Intent();
                        intent.setAction(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                        intent.setAction(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
                        intent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 200);
                    }
                    break;
                case R.id.stop:
                    bluetoothAdapter.disable();
                    list.clear();
                    myAdapter.notifyDataSetChanged();
                    break;
                case R.id.serach:
                    bluetoothAdapter.startDiscovery();
                    break;
            }
        }
    
        public class BluetoothReceiver extends BroadcastReceiver {
            @Override
            public void onReceive(Context context, Intent intent) {
                String action = intent.getAction();
                switch (action) {
                    case BluetoothDevice.ACTION_BOND_STATE_CHANGED:
                        BluetoothDevice bluetoothDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                        int state = bluetoothDevice.getBondState();
                        if (state == BluetoothDevice.BOND_BONDED) {
                            Log.e("###", "连接成功");
                        }
    
                        break;
                    case BluetoothDevice.ACTION_FOUND:
                        BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                        list.add(device);
                        myAdapter.notifyDataSetChanged();
                        break;
                    case BluetoothAdapter.ACTION_DISCOVERY_FINISHED:
                        myAdapter.notifyDataSetChanged();
                        break;
                }
            }
        }
    }
    
    

    ListView适配器

    package com.example.day10_2;
    
    import android.bluetooth.BluetoothDevice;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.BaseAdapter;
    import android.widget.TextView;
    
    import com.example.day10.R;
    
    import java.util.ArrayList;
    import java.util.List;
    
    class MyAdapter extends BaseAdapter {
        List<BluetoothDevice> list;
    
        public MyAdapter(List<BluetoothDevice> list) {
            this.list = list;
        }
    
        @Override
        public int getCount() {
            return list.size();
        }
    
        @Override
        public Object getItem(int position) {
            return null;
        }
    
        @Override
        public long getItemId(int position) {
            return position;
        }
    
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder viewHolder;
            if (convertView == null) {
                viewHolder = new ViewHolder();
                convertView = View.inflate(parent.getContext(), R.layout.list, null);
                viewHolder.name = convertView.findViewById(R.id.name);
                viewHolder.address = convertView.findViewById(R.id.address);
                convertView.setTag(viewHolder);
            } else {
                viewHolder = (ViewHolder) convertView.getTag();
                viewHolder.name.setText(list.get(position).getName());
                viewHolder.address.setText(list.get(position).getAddress());
            }
            return convertView;
        }
    
        public class ViewHolder {
            TextView name;
            TextView address;
        }
    }
    
    
    更多相关内容
  • 最新AS可以直接使用
  • 修改大佬的代码用于AndroidStudio,可以连接蓝牙和接收温度数据并绘制温度曲线
  • 完成两台手机的蓝牙数据传输功能,一台作为服务器,一台作为客户端,注意UUID得改一下,每台手机的UUID都不一样,可以在线调试代码查看当前手机的UUID
  • 这是很简洁的android 蓝牙和socket的范例,开发环境为android studio
  • 根据最新的AS整理,下载可直接运行,一些坑已经写好了
  • AndroidStudio蓝牙通信

    千次阅读 2021-12-13 20:53:08
    openBluetooth蓝牙开启函数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;
        }
    }
    

    四、运行界面展示

    在这里插入图片描述

    五、源码

    代码仓库:https://github.com/zhouyuqi1014/bluetooth

    展开全文
  • 点击“连接”按钮与周围的蓝牙设备进行配对,自动接收规定格式的信号,并显示对应的波形图、峰峰值、频率、THDx、五次谐波的归一化幅值 说明链接:https://blog.csdn.net/qq_39542170/article/details/121691497
  • 基于Android studio蓝牙开发代码,正在进行android程序开发的小伙伴可以看一下,可用于手环二次开发的蓝牙模块的书写。
  • app连接蓝牙模块2.0进行互相通讯,使用androidstudio编写,页面相对简单,但是功能完善,蓝牙必须先配对再在app中连接
  • 本软件为蓝牙串口通信工具,支持蓝牙从模式和主模式,可进行蓝牙串口通信测试。能连接单片机及PC的蓝牙串口。 可用于硬件的串口蓝牙模块(TTL)通信。 软件功能: 1、搜索蓝牙设备 2、接收显示数据与发送数据 3、可...
  • 以win10_64bit使用git为例: cd e: mkdir nordic-app cd nordic-app git clone https://github.com/NordicSemiconductor/nRF5-SDK-for-Mesh.git 注意查看github上的简介说明(for mesh的sdk配合sdk15.0.0)
  • Android studio蓝牙遥控

    2018-07-09 16:23:24
    Android studio 蓝牙通信,能与单片机(STM32等)进行通信,按下相关的按键能给单片机上的蓝牙HC05发送数据。
  •  刚开始学android studio,使用的是1.5版本,这是网上找的源代码,碰到这种报错就没办法了。程序可以下载到手机,点开后会提示打开蓝牙,打开蓝牙点击 “连接” 按钮准备配对就会...
  • 一种基于AndroidStudio的APP,通过蓝牙连接,绘制实时温度图
  • 这个代码在AndroidStudio上运行之后可以实现扫描wifi和蓝牙的功能,并将结果显示在一个列表中,点击列表可以连接wifi,没密码会直接连接,有密码的话,输入密码就可以连接
  • Android Studio 蓝牙通信BlueTooth

    千次阅读 2020-06-01 21:31:03
    BlueTooth蓝牙通信作业内容配置蓝牙使用权限页面布局Layout文件夹中Values文件夹中Menu文件夹中事件监听控制服务组件ChatService.javaweixinFragment.java实现界面展示 ...uses-permission android:n

    作业内容

    在类微信程序的第一子项中完成“蓝牙聊天功能”

    配置蓝牙使用权限

    在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;
        }
    

    实现界面展示

    Alt
    Alt

    模拟器蓝牙不可用。因身边无安卓系统手机,于是无法安装到手机上运行。

    附上源码: 蓝牙通信BlueTooth(Gitee).

    展开全文
  • android_studio手机蓝牙串口通信源代码,我自己已经下载到手机上调试过,可以用。讲解清楚,十分受用!
  • Android studio 蓝牙通讯

    2020-06-01 15:47:52
    搜索附近的蓝牙设备 与指定设备连接 连接成功后可以互发消息 结果截图 项目源码 GitHub:点此跳转 核心代码 开启一个 ConnectedThread 来管理对应的当前连接。之前先取消任意现存的 mConnectThread 、...

    参考文档

    blog:点此跳转

    项目相关

    项目功能

    1. 搜索附近的蓝牙设备
    2. 与指定设备连接
    3. 连接成功后可以互发消息

    结果截图

    在这里插入图片描述
    在这里插入图片描述
    在这里插入图片描述

    项目源码

    GitHub:点此跳转

    核心代码

    开启一个 ConnectedThread 来管理对应的当前连接。之前先取消任意现存的 mConnectThread 、mConnectedThread 、 mAcceptThread 线程,然后开启新 mConnectedThread ,传入当前刚刚接受的socket 连接。最后通过 Handler来通知UI连接

        public synchronized void connected(BluetoothSocket socket, BluetoothDevice device) {
            if (mConnectThread != null) {
                mConnectThread.cancel();
                mConnectThread = null;
            }
            if (mConnectedThread != null) {
                mConnectedThread.cancel();
                mConnectedThread = null;
            }
            if (mAcceptThread != null) {
                mAcceptThread.cancel();
                mAcceptThread = null;
            }
            mConnectedThread = new ConnectedThread(socket);
            mConnectedThread.start();
            Message msg = mHandler.obtainMessage(weixinFragment.MESSAGE_DEVICE_NAME);
            Bundle bundle = new Bundle();
            bundle.putString(weixinFragment.DEVICE_NAME, device.getName());
            msg.setData(bundle);
            mHandler.sendMessage(msg);
            setState(STATE_CONNECTED);
        }
    

    创建监听线程,准备接受新连接。使用阻塞方式,调用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;
            }
    

    双方蓝牙连接后一直运行的线程;构造函数中设置输入输出流。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();
                }
            }
        }
    
    展开全文
  • Android Studio蓝牙列表

    千次阅读 2019-06-18 21:21:48
    代码 Activity 注:小编这里编译是9.0,所以加了动态申请权限 ... import android.Manifest; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice;...import android.bluetooth.B...
  • 因项目需要做一个Android蓝牙app来通过手机蓝牙传输数据以及控制飞行器,... 该应用的Compile Sdk Version 和targetSdkVersion均为26,Min Sdk Version为22,基于Android studio平台开发。 一、声明蓝牙权限 ...
  • 无论是WIFI还是4G网络,建立网络连接后都是访问...Android蓝牙技术提供了4个工具类,分别是蓝牙适配器BluetoothAdapter、蓝牙设备BluetoothDevice、蓝牙服务端套接字BluetoothServerSocket和蓝牙客户端套接字Blueto
  • Android Studio 蓝牙开发流程

    万次阅读 多人点赞 2018-07-13 22:45:17
    1. 权限关于蓝牙的权限主要涉及到下面三个:BLUETOOTH:允许配对的设备进行连接BLUETOOTH_ADMIN:允许搜索和配对设备ACCESS_COARSE_LOCATION:广播接收器接收BluetoothDevice.ACTION_FOUND广播需要改权限 &...
  • 蓝牙ble调试工具 蓝牙 连接 通信 发送命令 显示硬件端数据 (专注于Android iOS 低功耗设备开发)
  • 本代码将蓝牙通信封装在一个API里,资源就在里面。代码实现了手机和蓝牙小车之间的通信
  • android studio——蓝牙通信

    千次阅读 2021-12-13 17:32:24
    文章目录一、结果展示二、核心代码1、AndroidManifest.xml文件2、MainActivity.java文件3、activity.xml文件 一、结果展示 点击“打开手机蓝牙”: ...uses-permission android:name="android.permission.BLUE
  • android实现蓝牙app代码

    2021-01-04 22:13:13
    本文实例为大家分享了android实现蓝牙app的具体代码,供大家参考,具体内容如下 private BluetoothGatt bluetoothGatt; private BluetoothGattService gattService; private BluetoothGattCharacteristic ...
  • Android Studio 经典蓝牙实现

    千次阅读 2022-02-14 14:23:11
    Android Studio 经典蓝牙实现
  • Android Studio开发蓝牙应用(一)

    千次阅读 热门讨论 2022-01-26 11:17:25
    Android Studio开发蓝牙应用(一) 环境 window 11 安卓12 HC-06蓝牙模块 创建空project 选择Empty Activity,后点击Next 可修改项目名,自定义,后点击Finish即可。 首先设计布局,布局文件位于app/src/...

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 5,146
精华内容 2,058
关键字:

android studio蓝牙