android蓝牙开发的一个小Dome

**

BluetoothAdapter 蓝牙适配器,即该类里面包含了蓝牙使用中常用到的一些API。 BroadcastReceiver
广播接收者,不难猜测,蓝牙设备开启或者关闭、搜索到周边设备就要来通知应用,那么Android系统就会以广播的方式来通知。
BluetoothDevice
蓝牙设备,即一个相当于蓝牙设备的类,实现了Parcelable接口,用于Android的IPC通信机制。里面实在广播时发送的蓝牙的相关信息:蓝牙名称,地址,类型和uuid等。

**
界面展示:
在这里插入图片描述
在这里插入图片描述

这个是目录结构
在这里插入图片描述
首先是蓝牙模块的控制层
BlueToothController

package com.example.bluetoothclass2;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Context;
import android.content.Intent;

import java.util.ArrayList;
import java.util.List;

/**
 * 蓝牙适配器
 *
 */
public class BlueToothController {
    private BluetoothAdapter mAdapter;
    public BluetoothAdapter getAdapter() {
        return mAdapter;
    }
    public BlueToothController(){
        mAdapter = BluetoothAdapter.getDefaultAdapter();
    }
    /**
     * 是否支持蓝牙
     */
  public boolean isSupportBlueTooth(){
      if (mAdapter!= null){
          return true;
      }
      else {
          return false;
      }
  }
  public boolean getBlueToothStatus(){
      assert (mAdapter!=null);
      return mAdapter.isEnabled();
  }

    /**
     * 打开蓝牙
     * @param activity
     * @param requestCode
     */
  public void turnOnBlueTooth(Activity activity, int requestCode){
      Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
      activity.startActivityForResult(intent, requestCode);

  }
//    /**
//     * 打开蓝牙可见性
//     */
//    public void enableVisibily(Context context){
//        Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
//        intent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION,300);
//        context.startActivity(intent);
//    }
    /**
     * 打开蓝牙可见性
     * @param context
     */
    public void enableVisibly(Context context) {
        Intent discoverableIntent = new
                Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
        discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
        context.startActivity(discoverableIntent);
    }
    /**
     * 查找设备
     */
    public void findDevice() {
        assert (mAdapter != null);
        mAdapter.startDiscovery();
    }
    /**
     * 关闭蓝牙
     */
    public void turnOffBlueTooth() {
        mAdapter.disable();
    }
    /**
     * 获取已绑定设备
     */
    public List<BluetoothDevice> getBondedDeviceList(){
        return new ArrayList<>(mAdapter.getBondedDevices());
    }


}

然后是是适配器
DeviceListAdapter

package com.example.bluetoothclass2;

import android.bluetooth.BluetoothDevice;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import java.util.List;

public class DeviceListAdapter extends RecyclerView.Adapter<DeviceListAdapter.ViewHolder> {
    private List<BluetoothDevice> devices;

    public DeviceListAdapter(List<BluetoothDevice> devices) {
        this.devices = devices;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View inflate = LayoutInflater.from(parent.getContext()).inflate(R.layout.item, parent, false);
        ViewHolder viewHolder = new ViewHolder(inflate);
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        BluetoothDevice bluetoothDevice = devices.get(position);
        holder.title.setText(bluetoothDevice.getName());
    }

    @Override
    public int getItemCount() {
        return devices != null ? devices.size() : 0;
    }

    class ViewHolder extends RecyclerView.ViewHolder {
        private TextView title;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            title = itemView.findViewById(R.id.name);
        }
    }
}

这个MainActivity主要负责第一个界面的功能内容

package com.example.bluetoothclass2;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.bluetooth.BluetoothAdapter;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    private static final int REQUEST_COOE =0;
    private BlueToothController mController= new BlueToothController();
    private Toast mToast;
    private Button button;
    private BroadcastReceiver receiver =new BroadcastReceiver() {
         @Override
         public void onReceive(Context context, Intent intent) {
             int state =intent.getIntExtra(BluetoothAdapter.EXTRA_STATE,-1);
             switch (state){
                 case BluetoothAdapter.STATE_OFF:
                     showToast("STATE_OFF");
                     break;
                 case BluetoothAdapter.STATE_ON:
                     showToast("STATE_ON");
                     break;
                 case BluetoothAdapter.STATE_TURNING_ON:
                     showToast("STATE_TURNING_ON");
                 case BluetoothAdapter.STATE_TURNING_OFF:
                      showToast("STATE_TURNING_OFF");
                      break;
                 default:
                     showToast("Unkown STATE");
                     break;
             }
         }
     };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        IntentFilter filter =new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
        registerReceiver(receiver,filter);
        button=(Button) findViewById(R.id.bt_ss);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(MainActivity.this,MainActivity2.class);
                startActivity(intent);
            }
        });
    }

    public void isSupportBlueTooth(View view){
      boolean ret =mController.isSupportBlueTooth();
      showToast("support Bluetooth?"+ret);
    }
    public void isBlueToothEnable(View view){
       boolean ret=mController.getBlueToothStatus();
       showToast("Bluetooth enable?"  +ret);
    }
    public void requestTurnOnBlueTooth(View view){
        mController.turnOnBlueTooth(this, REQUEST_COOE);
    }
    public void turnOffBlueTooth(View view){
        mController.turnOffBlueTooth();
    }
    private void showToast(String text){
         if (mToast==null){
             mToast=Toast.makeText(this,text,Toast.LENGTH_SHORT);
         }
         else {
             mToast.setText(text);
         }
         mToast.show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode==RESULT_OK){
            showToast("打开成功");
        }
        else {
            showToast("打开失败");
        }
    }
}

MainActivity2负责扫描附近蓝牙设备

package com.example.bluetoothclass2;

import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;

import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class MainActivity2 extends AppCompatActivity {
    private BluetoothAdapter bluetoothAdapter;
    private static final String TAG = "MainActivity";
    private Map<String, BluetoothDevice> deviceMap = new ConcurrentHashMap<>();
    private RecyclerView recyclerView = null;
    private RecyclerView.Adapter adapter = null;
    private final BroadcastReceiver receiver = new BroadcastReceiver() {
        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 (!deviceMap.containsKey(device.getAddress())) {
                    deviceMap.put(device.getAddress(), device);
                    if (device.getName() != null && !"".equals(device.getName())){
                        devices.add(device);
                        adapter.notifyDataSetChanged();
                    }
                }
            }
        }
    };
    private List<BluetoothDevice> devices = Collections.synchronizedList(new ArrayList<>());

    private void registerBroadcast() {
        IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        registerReceiver(receiver, filter);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(receiver);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
        registerBroadcast();
        permissionGet();
        bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (bluetoothAdapter == null) {
            Toast.makeText(this, "This device doesn't support Bluetooth",
                    Toast.LENGTH_LONG).show();
        }
        if (bluetoothAdapter.isEnabled()) {
            // 如果蓝牙功能已开启
            if (bluetoothAdapter.isDiscovering()) {
                // 如果正在执行“发现设备”操作
                bluetoothAdapter.cancelDiscovery();
            }
            if (bluetoothAdapter.startDiscovery()) {
                Toast.makeText(this, "正在扫描", Toast.LENGTH_SHORT).show();
            }
        }
        recyclerView = findViewById(R.id.list);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        adapter = new DeviceListAdapter(devices);
        recyclerView.setAdapter(adapter);
    }

    private void permissionGet() {
        requestPermissions(new String[]{
                Manifest.permission.ACCESS_COARSE_LOCATION,
                Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.ACCESS_BACKGROUND_LOCATION}, 200);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        Log.d(TAG, "onRequestPermissionsResult: " + requestCode);
        for (int i = 0; i < permissions.length; i++) {
            Log.d("permission", permissions[i] + "  is  " + grantResults[i]);
            if (grantResults[i] == -1) {
                Toast.makeText(this, "请为应用授权" + permissions[i], Toast.LENGTH_SHORT).show();
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

    }
}

界面文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <Button

        android:id="@+id/is_support_blue_tooth"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="isSupportBlueTooth"
        android:text="是否支持蓝牙" />

    <Button
        android:id="@+id/is_blue_tooth_enable"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="isBlueToothEnable"
        android:text="蓝牙是否打开" />

    <Button
        android:id="@+id/turn_on_blue_tooth"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="requestTurnOnBlueTooth"
        android:text="请求去打开蓝牙" />

    <Button
        android:id="@+id/turn_off_blue_tooth"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="turnOffBlueTooth"
        android:text="关闭蓝牙" />

    <Button
        android:id="@+id/bt_ss"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="搜索附近蓝牙设备" />
</LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity2">
    <androidx.appcompat.widget.Toolbar
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        android:id="@+id/toolBar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <TextView
            android:layout_gravity="center"
            android:text="附近的设备"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content">

        </TextView>
    </androidx.appcompat.widget.Toolbar>
    <androidx.recyclerview.widget.RecyclerView
        app:layout_constraintTop_toBottomOf="@id/toolBar"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintVertical_weight="1"
        app:layout_constraintBottom_toBottomOf="parent"
        android:id="@+id/list"
        android:layout_width="match_parent"
        android:layout_height="0dp">

    </androidx.recyclerview.widget.RecyclerView>
</androidx.constraintlayout.widget.ConstraintLayout>
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <ImageView
        android:src="@drawable/ic_launcher_background"
        android:id="@+id/icon"
        android:layout_width="50dp"
        android:layout_height="50dp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintTop_toTopOf="parent"></ImageView>

    <TextView
        android:id="@+id/name"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:textSize="18sp"
        android:text="aa"
        android:textAlignment="center"
        app:layout_constraintHorizontal_weight="1"
        app:layout_constraintLeft_toRightOf="@id/icon"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"></TextView>
</androidx.constraintlayout.widget.ConstraintLayout>

AndroidManifest.xml文件

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="com.example.bluetoothclass2">
    <uses-permission android:name="android.permission.BLUETOOTH"/>
    <uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION"></uses-permission>
    <uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
    <uses-permission android:name="android.permission.BLUETOOTH_SCAN" />

    <application
        android:allowBackup="true"
        android:dataExtractionRules="@xml/data_extraction_rules"
        android:fullBackupContent="@xml/backup_rules"
        android:icon="@mipmap/ic_launcher"
        android:label="蓝牙"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.BlueToothClass2"
        tools:targetApi="31">
        <activity
            android:name=".MainActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <activity android:name=".MainActivity2"/>
    </application>

</manifest>

这样就可以了,希望可以给学习安卓蓝牙开发的小伙伴一些帮助。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Android是一种基于Linux内核(不包含GNU组件)的自由及开放源代码的移动操作系统,主要应用于移动设备,如智能手机和平板电脑。该系统最初由安迪·鲁宾开发,后被Google公司收购并注资,随后与多家硬件制造商、软件开发商及电信营运商共同研发改良。 Android操作系统的特点包括: 开放源代码:Android系统采用开放源代码模式,允许开发者自由访问、修改和定制操作系统,这促进了技术的创新和发展,使得Android系统具有高度的灵活性和可定制性。 多任务处理:Android允许用户同时运行多个应用程序,并且可以轻松地在不同应用程序之间切换,提高了效率和便利性。 丰富的应用生态系统:Android系统拥有庞大的应用程序生态系统,用户可以从Google Play商店或其他第三方应用市场下载和安装各种各样的应用程序,满足各种需求。 可定制性:Android操作系统可以根据用户的个人喜好进行定制,用户可以更改主题、小部件和图标等,以使其界面更符合个人风格和偏好。 多种设备支持:Android操作系统可以运行在多种不同类型的设备上,包括手机、平板电脑、智能电视、汽车导航系统等。 此外,Android系统还有一些常见的问题,如应用崩溃、电池耗电过快、Wi-Fi连接问题、存储空间不足、更新问题等。针对这些问题,用户可以尝试一些基本的解决方法,如清除应用缓存和数据、降低屏幕亮度、关闭没有使用的连接和传感器、限制后台运行的应用、删除不需要的文件和应用等。 随着Android系统的不断发展,其功能和性能也在不断提升。例如,最新的Android版本引入了更多的安全性和隐私保护功能,以及更流畅的用户界面和更强大的性能。此外,Android系统也在不断探索新的应用场景,如智能家居、虚拟现实、人工智能等领域。 总之,Android系统是一种功能强大、灵活可定制、拥有丰富应用生态系统的移动操作系统,在全球范围内拥有广泛的用户基础。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

那天的烟花雨

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值