我正在开发一个单独的BluetoothHelper课程。在connectToBTDevice()方法中,调用一个新线程,在线程中,蓝牙套接字试图连接到蓝牙设备。不幸的是,它开始很好,但退出时发出警告System.err如下:

04-11 20:46:15.711 2848-2848/? D/BluetoothHelper﹕ Connecting...name: Zakariya , address: 84:55:A5:8C:2E:2A

04-11 20:46:17.710 2848-3300/? W/System.err﹕ at com.prome.bluetoothdevicecontroller.helpers.BluetoothHelper.run(BluetoothHelper.java:262)

04-11 20:46:17.710 2848-3300/? D/BluetoothHelper﹕ could not connect to device

04-11 20:46:17.718 2848-3300/? D/BluetoothHelper﹕ socket closed

BluetoothHelper.java

package com.prome.bluetoothdevicecontroller.helpers;

import android.app.Activity;

import android.app.ProgressDialog;

import android.bluetooth.BluetoothAdapter;

import android.bluetooth.BluetoothDevice;

import android.bluetooth.BluetoothServerSocket;

import android.bluetooth.BluetoothSocket;

import android.content.BroadcastReceiver;

import android.content.Context;

import android.content.Intent;

import android.content.IntentFilter;

import android.os.Handler;

import android.os.Message;

import android.util.Log;

import com.prome.bluetoothdevicecontroller.activities.MainActivity;

import java.io.IOException;

import java.util.ArrayList;

import java.util.Set;

import java.util.UUID;

/**

* Bluetooth helper class

*

* @author Md. Nabid Imteaj

* @version 1.0

* @see android.bluetooth.BluetoothAdapter

* @see http://developer.android.com/guide/topics/connectivity/bluetooth.html

*/

public class BluetoothHelper implements Runnable {

// tag

public static final String TAG = "BluetoothHelper";

// make it singleton

private static BluetoothHelper bluetoothHelper = null;

// bluetooth adapter

private static BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

// local integer > 0, taking random int which may not conflict

// with other requestCode

public static final int REQUEST_ENABLE_BT = 1001;

// save found bluetooth devices in range

ArrayList foundDevices = new ArrayList<>();

// progress dialog

ProgressDialog progress;

// socket

private BluetoothSocket mBluetoothSocket;

private BluetoothServerSocket mBluetoothServerSocket;

// uuid

private UUID uuid = UUID.randomUUID();

// bluetooth device

private BluetoothDevice bluetoothDevice;

// save context

private Context context;

// constructor

private BluetoothHelper(Context context) {

this.context = context;

}

/**

* Returns new instance if not created, previous instance otherwise

*

* @return bluetoothHelper

*/

public static BluetoothHelper getInstance(Context context) {

if(bluetoothHelper == null) bluetoothHelper = new BluetoothHelper(context);

return bluetoothHelper;

}

/**

* Checks the device is Bluetooth supported or not

*

* @return true if the device is Bluetooth supported, false otherwise

*/

public boolean isBluetoothSupported() {

if(bluetoothAdapter == null) return false;

return true;

}

/**

* Enables Bluetooth

*

* @param context

* @see android.app.Activity

*/

public void enableBluetooth(Activity context) {

if(!bluetoothAdapter.isEnabled()) {

Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);

// note: onActivityResult() must be implemented in the parent activity

// in our case it is defined in MainActivity

context.startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);

// save context for future use

//this.context = context;

}

}

/**

* Returns paired devices connected with this device

*

* @return deviceList

*/

public ArrayList getPairedDevices() {

Set pairedDevices = bluetoothAdapter.getBondedDevices();

ArrayList deviceList = new ArrayList<>();

// check has paired devices or not

if(pairedDevices.size() > 0) {

// initiate array list

//deviceList = new ArrayList<>();

// get names, address and its type

for(BluetoothDevice device : pairedDevices) {

//deviceList.add(device.getName() + "\n" + device.getAddress());

deviceList.add(device);

}

}

return deviceList;

}

/**

* Disables bluetooth

*/

public void disableBluetooth() {

bluetoothAdapter.disable();

}

/**

* Cancel discovering devices

* Must add it in onDestroy() of an activity or fragment

*/

public void cancelDiscovery(Context context) {

// if bluetooth is supported and is discovering devices

// then cancel discovering devices

if(bluetoothAdapter != null && bluetoothAdapter.isDiscovering()) {

bluetoothAdapter.cancelDiscovery();

// unregister receiver

context.unregisterReceiver(mReceiver);

}

}

/**

* Start discovering bluetooth devices in range

*

* @param context

*/

public void startDiscovery(Context context) {

// get a new IntentFilter

IntentFilter filter = new IntentFilter();

filter.addAction(BluetoothDevice.ACTION_FOUND);

filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);

filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);

// register broadcast receiver

context.registerReceiver(mReceiver, filter);

bluetoothAdapter.startDiscovery();

}

private void showProgress(Context context, String message) {

progress = new ProgressDialog(context);

progress.setMessage(message);

progress.setProgressStyle(ProgressDialog.STYLE_SPINNER);

progress.setIndeterminate(true);

progress.setCancelable(false);

progress.setCanceledOnTouchOutside(false);

progress.show();

}

private void hideProgress() {

if(progress.isShowing()) {

progress.dismiss();

}

}

private final BroadcastReceiver mReceiver = new BroadcastReceiver() {

public void onReceive(Context context, Intent intent) {

String action = intent.getAction();

if(BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) {

//discovery starts, we can show progress dialog or perform other tasks

Log.d(BluetoothHelper.TAG, "discovery started");

// clear previous list

foundDevices.clear();

// show loading dialog

showProgress(context, "Scanning devices...");

} else if(BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {

//discovery finishes, dismis progress dialog

Log.d(BluetoothHelper.TAG, "discovery finished");

// hide progress dialog

hideProgress();

// show found devices

((MainActivity) context).startDeviceListDialog("Paired Devices", foundDevices);

} else if(BluetoothDevice.ACTION_FOUND.equals(action)) {

//bluetooth device found

BluetoothDevice device = (BluetoothDevice) intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);

// insert this device into foundDevice array list

foundDevices.add(device);

//showToast("Found device " + device.getName());

Log.d(BluetoothHelper.TAG, "found: " + device.getName() + ", " + device.getAddress());

}

}

};

/**

* Returns found devices by searching in range

*

* @return ArrayList

*/

public ArrayList getFoundDevices() {

return foundDevices;

}

public void connectToBTDevice(BluetoothDevice device) {

// get bluetooth device by address

bluetoothDevice = bluetoothAdapter.getRemoteDevice(device.getAddress());

// show dialog connecting

showProgress(context, "Connecting..."+"\n"+device.getName()+"\n"+device.getAddress());

Log.d(BluetoothHelper.TAG, "Connecting..."+"name: "+device.getName()+", address: "+device.getAddress());

// create new thread

Thread bluetoothConnectThread = new Thread(this);

// start thread

bluetoothConnectThread.start();

//pairToDevice(mBluetoothDevice); This method is replaced by progress dialog with thread

}

// thread to connect with bluetooth device

@Override

public void run() {

try {

// open socket

uuid = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb");

mBluetoothSocket = bluetoothDevice.createRfcommSocketToServiceRecord(uuid);

// cancel discovering

//cancelDiscovery(context);

// already cancelled

// connect through socket

mBluetoothSocket.connect();

Log.d(BluetoothHelper.TAG, "connected to device");

// send empty message

//mHandler.sendEmptyMessage(0);

} catch(IOException e) {

e.printStackTrace();

Log.d(BluetoothHelper.TAG, "could not connect to device");

//hide progress bar

hideProgress();

// close the socket

try {

mBluetoothSocket.close();

Log.d(BluetoothHelper.TAG, "socket closed");

} catch(IOException e1) {

e1.printStackTrace();

Log.d(BluetoothHelper.TAG, "socket could not be closed");

}

}

}

private Handler mHandler = new Handler() {

@Override

public void handleMessage(Message msg) {

hideProgress();

Log.d(BluetoothHelper.TAG, "connected with device");

}

};

/**

* make the device discoverable within 300 seconds

*/

public void makeDiscoverable() {

// create new intent

Intent discoverableIntent = new

Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);

discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);

context.startActivity(discoverableIntent);

}

}

onnectToBTDevice(BluetoothDevice device)方法位于第234行.BluetoothSocket connect()方法不适用于配对和非配对设备。

android蓝牙连接回调没反应,Android蓝牙套接字连接无法正常工作相关推荐

  1. 向一个无法连接的网络尝试了一个套接字操作_python3从零学习-5.8.1、socket—底层网络接口...

    源代码: Lib/socket.py 这个模块提供了访问BSD*套接字*的接口.在所有现代Unix系统.Windows.macOS和其他一些平台上可用. 这个Python接口是用Python的面向对象 ...

  2. 【苹果群发】内容Apple推送iMessage服务器和iOS手机操作系统之间的套接字连接PushNotificationDemo

    推荐内容IMESSGAE相关 作者推荐内容 iMessage苹果推软件 *** 点击即可查看作者要求内容信息 作者推荐内容 1.家庭推内容 *** 点击即可查看作者要求内容信息 作者推荐内容 2.相册 ...

  3. [转]如何借助 TLS/SSL 确保套接字连接的安全(使用 C#/VB/C++ 和 XAML 的 Windows 应用商店应用)...

    本文转自:http://msdn.microsoft.com/zh-cn/library/windows/apps/jj150597.aspx 本主题将展示在使用 StreamSocket 功能时,如 ...

  4. mysal向一个无法连接的网络尝试了一个套接字操作 0.0.3.235_第十二章 Java网络编程(3)——套接字(上)...

    套接字 套接字概述 网络通信使用IP地址标识Internet上的计算机,使用端口号标识服务器上的进程(程序).也就是说,如果服务器上的一个程序不占用一个端口号,用户程序就无法找到它,就无法和该程序交互 ...

  5. WCF分布式开发常见错误(10):套接字连接中断,The socket connection was aborted

    (使用Windows Service作为宿主的时候也会出现这样的情况,搜索的) 我们这里是自定义托管宿主,在进行WCF编程开发过程时,使用NetTcpBinding绑定协议,作为通讯协议,可能会引发这 ...

  6. 打开VM虚拟机,遇见问题“无法连接MKS:套接字连接次数太多;正在放弃。”

    问题 "无法连接MKS:套接字连接次数太多:正在放弃." 解决办法 右键"开始" 选择"计算机管理" 在"服务"里找到V ...

  7. VmWare工作笔记001---弹出错误提示无法连接mks:套接字连接尝试次数太多

    技术交流QQ群[JAVA,.NET,BigData,AI]:170933152 弹出错误提示无法连接mks:套接字连接尝试次数太多,这时我们点击确定按钮. 这个直接到服务中,看看有没有VMware的服 ...

  8. Win 7 安装VMware Workstation Pro 14出现 “Intel VT-x禁用”问题以及“无法连接 MKS: 套接字连接尝试次数太多;正在放弃”问题的实质性解决

    Win 7 安装VMware Workstation Pro 14出现 "Intel VT-x禁用"问题以及"无法连接 MKS: 套接字连接尝试次数太多:正在放弃&quo ...

  9. android网络请求回调管理,Android网络请求回调没正常走 处理方案

    处理类 import android.os.Handler; import android.os.Looper; import android.os.Message; /** * * 考虑可能回调没正 ...

最新文章

  1. AutoFac使用方法总结:Part I
  2. Java算法(两数之和)
  3. VIM - 每行前或者每行后增加相同的字符串
  4. 解锁三星bl锁有几种方法_三星S6解锁教程_三星GALAXY S6怎么解锁Bootloader的方法
  5. Spring Cloud Security:Oauth2结合JWT使用
  6. Linux 命令之 df -- 显示磁盘空间使用情况
  7. mysql数据应用从入门_MYSQL数据库应用从入门到精通----读书笔记
  8. ZED ROS包发布topic介绍
  9. UVA 10340 - All in All
  10. 如何实现A星寻路算法 Cocos2d-x 3.0 beta2
  11. android搜狗离线安装包,搜狗翻译离线版下载
  12. Unity 常用脚本:ScreenCapture
  13. GTD工具 Wunderlist使用心得总结
  14. Sphero SPRK+,和星战的 BB-8 一样,这个球也是机器人 | 新玩意 · Apple Store
  15. docker build stress命令
  16. linux下火狐浏览器如何安装flash插件
  17. 学习小甲鱼Python入门(二)习题笔记-列表
  18. surface android模拟,Surface Duo将支持Android小部件 模拟磁铁体验
  19. Excel表格设置下拉选项并应用到整列及清除下拉项设置
  20. 制作表白墙,给TA一个惊喜吧

热门文章

  1. 【话题】致敬伟大的科学家史蒂芬·霍金,他留下的预言能实现吗?
  2. cpld xilinx 定义全局时钟_Xilinx+CPLD介绍
  3. 如何领取鸿蒙开发板,如何获取鸿蒙开发板?鸿蒙开发板免费试用通道!
  4. java人体识别_【人体分析-人像分割】JavaAPI示例代码
  5. 1. 无法解析的外部符号 “__declspec(dllimport) const XXX::vftable“ ` 2. `无法定义 dllimport 实体`
  6. 服务器宕机 自动重启,服务器宕机重启利弊
  7. 通过BSSID和无线流量传输后门Payload
  8. win .net 问题汇总
  9. 用手机GPRS使电脑上网
  10. 机器学习之朴素贝叶斯实现垃圾邮件过滤