Android Bluetooth蓝牙客户端发起对服务端连接建立请求过程(高版本Android兼容)

标签: android
640人阅读 评论(1) 收藏 举报
分类:

Android Bluetooth蓝牙客户端发起对服务端连接建立请求过程(高版本Android兼容)


本例代码是蓝牙客户端代码,只完成连接建立请求,假定蓝牙服务端设备名是:Android-Phone。兼容高版本Android系统。低版本则无需运行时权限申请。

package zhangphil.client;

import java.util.UUID;

import android.Manifest;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;

public class MainActivity extends Activity {

    private BluetoothAdapter mBluetoothAdapter;

    private final int PERMISSION_REQUEST_COARSE_LOCATION = 0xb01;

    private String TAG = "zhangphil";
    private String MY_UUID = "00001101-0000-1000-8000-00805F9B34FB";

    // 广播接收发现蓝牙设备
    private 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 != null) {
                    String name = device.getName();
                    Log.d(TAG, "发现设备:" + name);

                    if (TextUtils.equals(name, "Android-Phone")) {
                        Log.d(TAG, "发现目标设备,开始线程连接!");
                        // 蓝牙搜索是非常消耗系统资源开销的过程.
                        // 一旦发现了目标感兴趣的设备,可以考虑关闭扫描。
                        mBluetoothAdapter.cancelDiscovery();

                        new ClientThread(device).start();
                    }
                }
            }
        }
    };

    private class ClientThread extends Thread {

        private BluetoothDevice device;

        public ClientThread(BluetoothDevice device) {
            this.device = device;
        }

        @Override
        public void run() {
            BluetoothSocket socket;

            try {
                socket = device.createRfcommSocketToServiceRecord(UUID.fromString(MY_UUID));

                Log.d(TAG, "连接服务端...");
                socket.connect();
                Log.d(TAG, "连接建立.");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (this.checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, PERMISSION_REQUEST_COARSE_LOCATION);
            }
        }

        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

        // 注册广播接收器。接收蓝牙发现讯息
        IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        registerReceiver(mReceiver, filter);

        if (mBluetoothAdapter.startDiscovery()) {
            Log.d(TAG, "启动蓝牙扫描设备...");
        }
    }

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

    @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
        switch (requestCode) {
            case PERMISSION_REQUEST_COARSE_LOCATION:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                }

                break;
        }
    }
}

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:1412384次
    • 积分:18579
    • 等级:
    • 排名:第558名
    • 原创:509篇
    • 转载:13篇
    • 译文:2篇
    • 评论:270条
    关于我
    邮箱: zhangphil@live.com
    博客专栏
    最新评论