二、搜索蓝牙并连接(安卓蓝牙ble教程)

1、MainActivity.java

注:如果复制代码进项目时显示红色,请按ALT+ENTER键导包(import class)

 

package club.stm32;

import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;


public class MainActivity extends AppCompatActivity {

    private BluetoothAdapter bluetoothAdapter;
    private Button btnCheckPermission;
    private TextView tvmsg;
    private Button btnSearchBLE;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        getPermission();  //获取权限
        bluetoothInit();    //蓝牙初始化
        widgetInit();       //控件初始化
        widgetListener();   //控件监听

    }

    //获取权限
    private void getPermission() {

        //如果sdk版本大于23
        if (Build.VERSION.SDK_INT >=23){

            //如果没有权限
            if ((ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED))
            {
                //动态申请权限
                ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 10);

            }
        }
    }

    //控件初始化
    private void widgetInit() {

        //请自行提升到全局,原型是:Button startscan = findViewById(R.id.startscan);
        btnCheckPermission = findViewById(R.id.btnCheckPermission);

        //请自行提升到全局,原型是:TextView tvmsg = findViewById(R.id.tvmsg);
        tvmsg = findViewById(R.id.tvmsg);

        //请自行提升到全局,原型是:Button btnSearchBLE = findViewById(R.id.btnSearchBLE);
        btnSearchBLE = findViewById(R.id.btnSearchBLE);
    }

    //控件监听
    private void widgetListener() {

        //测试权限按钮监听
        btnCheckPermission.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int permissionCheck = ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION);
                if (permissionCheck == PackageManager.PERMISSION_GRANTED) {//如果有权限
                    Toast.makeText(MainActivity.this, "hava this permission", Toast.LENGTH_SHORT).show();//toast信息
                    Log.d("权限:","有定位权限");//在logcat上打印信息
                    tvmsg.setText("有定位权限");
                }else {
                    getPermission();//获取权限
                    Toast.makeText(MainActivity.this, "no this permission", Toast.LENGTH_SHORT).show();//toast信息
                    Log.d("权限:","无定位权限");//在logcat上打印信息
                    tvmsg.setText("无定位权限");
                }
            }
        });

        //搜索蓝牙按钮监听
        btnSearchBLE.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //开始搜索蓝牙
                bluetoothAdapter.startLeScan(mBLEScanCallback);
            }
        });

    }

    //mBLEScanCallback回调函数
    private BluetoothAdapter.LeScanCallback mBLEScanCallback = new BluetoothAdapter.LeScanCallback() {
        @Override
        public void onLeScan(BluetoothDevice device, int rssi, byte[] scanRecord) {
            
            //打印蓝牙mac地址
            Log.d("BleMAC", device.getAddress());
        }
    };



    private void bluetoothInit() {

        //如果不支持蓝牙
        if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE))
        {
            //提示不支持蓝牙
            Toast.makeText(this, "程序不支持该设备", Toast.LENGTH_SHORT).show();
            //退出程序
            finish();
        }
        //创建蓝牙适配器原型是BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        //如果蓝牙适配器为空
        if (bluetoothAdapter == null)
        {
            //显示设备无蓝牙
            Toast.makeText(this, "设备无蓝牙", Toast.LENGTH_SHORT).show();
            //退出
            finish();
        }
        //如果蓝牙未开启
        if (!bluetoothAdapter.isEnabled())
        {
            //不提示,直接开启蓝牙
            bluetoothAdapter.enable();
            //提示开启蓝牙中
            Toast.makeText(this, "开启蓝牙中,如果未开启,请检查应用权限", Toast.LENGTH_SHORT).show();
        }
    }
}

2、布局文件activity_main.xml




    
    

        

效果图:

二、搜索蓝牙并连接(安卓蓝牙ble教程)_第1张图片

 

注:如果你照我上面这样写,十有八九是搜不到蓝牙信息的,为什么呢,需要打开手机定位服务才能搜索到

另一种解决办法,是在build.gradle中配置如下信息

    lintOptions {
        checkReleaseBuilds false
        abortOnError false
    }

以及修改build.gradle中的targetSdkVersion ,修改到20或21可以解决定位权限问题

具体配置如下

apply plugin: 'com.android.application'
 
android {
    lintOptions {
        checkReleaseBuilds false
        abortOnError false
    }
    compileSdkVersion 28
    defaultConfig {
        applicationId "club.stm32"
        minSdkVersion 18
        targetSdkVersion 21
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}
 
dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:28.0.0'
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}

 

 

 

 

 

 

 

 

 

你可能感兴趣的:(ble,蓝牙,android,java)