Android Bluetooth使用详解

来源:网络 责任编辑:栏目编辑 发表时间:2013-07-02 01:22 点击:

1.判断是否支持Bluetooth
BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if(bluetoothAdapter == null) {
    //the device doesn't support bluetooth
} else {
    //the device support bluetooth
}

2.如果支持,打开Bluetooth

if(!bluetoothAdapter.isEnable()) {
    Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
    startActivityForResult(enableIntent,REQUEST_ENABLE_BT);
}

3.监视Bluetooth打开状态

BroadcastReceiver bluetoothState = new BroadcastReceiver() {
    public void onReceive(Context context, Intent intent) {
    String stateExtra = BluetoothAdapter.EXTRA_STATE;
       int state = intent.getIntExtra(stateExtra, -1);
       switch(state) {
    case BluetoothAdapter.STATE_TURNING_ON:
        break;
    case BluetoothAdapter.STATE_ON:
        break;
    case BluetoothAdapter.STATE_TURNING_OFF:
        break;
    case BluetoothAdapter.STATE_OFF:
        break;
    }
    }
}

registerReceiver(bluetoothState,new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED));

4.设置本地设备可以被其它设备搜索
Intent discoveryIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
startActivityForResult(discoveryIntent,REQUEST_DISCOVERY);

BroadcastReceiver discovery = new BroadcastReceiver() {
    @Override
    public void onRecevie(Content context, Intent intent) {
        String scanMode = BluetoothAdapter.EXTRA_SCAN_MODE;
        String preScanMode = BluetoothAdapter.EXTRA_PREVIOUS_SCAN_MODE;
        int mode = intent.getIntExtra(scanMode);
    }
}

registerReceiver(discovery,new IntentFilter(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED);

5.搜索设备
开始搜索 bluetoothAdapter.startDiscovery();
停止搜索 bluetoothAdapter.cancelDiscovery();

当发现一个设备时,系统会发出ACTION_FOUND广播消息,我们可以实现接收这个消息的BroadcastReceiver

BroadcastReceiver deviceFound = new BroadcastReceiver() {
    @Override
    public void onReceiver(Content content, Intent intent) {
        String remoteDeviceName = intent.getStringExtra(BluetoothAdapter.EXTRA_NAME);
        BluetoothDevice remoteDevice = intent.getParcelableExtra(BluetoothAdapter.EXTRA_DEVICE);
    }
}

registerReceiver(deviceFound, new IntentFilter(BluetoothAdapter.ACTION_FOUND);

摘自:zzqLivecn的专栏

    相关新闻>>

      发表评论
      请自觉遵守互联网相关的政策法规,严禁发布色情、暴力、反动的言论。
      用户名: 验证码:点击我更换图片
      最新评论 更多>>

      推荐热点

      • Android 完全退出程序
      • 原创:Android应用开发-Andorid歌词秀,含源码
      • android 屏幕保护
      • Android手机软件汉化教程---第四课 dex文件汉化
      • 众多Android 开源项目推荐,给力工作给力学习
      • Android Audio代码分析4
      • Android得到已安装的应用程序信息!
      • Android开发者指南(29) —— USB Host and Accessory
      • Android成长的幕后推手:工程师鲁宾
      网站首页 - 友情链接 - 网站地图 - TAG标签 - RSS订阅 - 内容搜索
      Copyright © 2008-2015 计算机技术学习交流网. 版权所有

      豫ICP备11007008号-1