Android中发现蓝牙设备的广播是,Android中的蓝牙设备发现 – startDiscovery()

目标:构建一个

Android应用程序,发现范围内BT设备的名称和地址,并将其值提交给Web服务. BT设备以前没有绑定到主机设备,我只想在我走路时轮询一切.

我做了什么

>编写文档.

>实现主机设备的BT适配器的本地实例.

>如果未启用BT,则实施通知以启用BT.

>注册的广播接收者和意图来解析startDiscovery()中的ACTION_FOUNDs.

>在清单中注册BLUETOOTH和BLUETOOTH_ADMIN权限.

事情工作(通过增量控制台日志记录测试)直到startDiscovery().

挫折:

> startDiscovery() – 我怀疑我在错误的上下文中传递这个.这种方法需要放在哪里才能正常运行?

如果你能够使这个方法工作,我将非常感谢你的智慧.

更新 – 这是一个被删除的简化版本的代码,导致我的悲伤;这个简化总结了我的错误.这段代码运行,它不会引发cat.log错误或其他错误,它根本不给出任何输出.

package aqu.bttest;

import android.app.Activity;

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.widget.Toast;

public class BT2Activity extends Activity {

private BluetoothAdapter mBTA;

private SingBroadcastReceiver mReceiver;

/** Called when the activity is first created. */

@Override

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.main);

//register local BT adapter

mBTA = BluetoothAdapter.getDefaultAdapter();

//check to see if there is BT on the Android device at all

if (mBTA == null){

int duration = Toast.LENGTH_SHORT;

Toast.makeText(this, "No Bluetooth on this handset", duration).show();

}

//let's make the user enable BT if it isn't already

if (!mBTA.isEnabled()){

Intent enableBT = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);

startActivityForResult(enableBT, 0xDEADBEEF);

}

//cancel any prior BT device discovery

if (mBTA.isDiscovering()){

mBTA.cancelDiscovery();

}

//re-start discovery

mBTA.startDiscovery();

//let's make a broadcast receiver to register our things

mReceiver = new SingBroadcastReceiver();

IntentFilter ifilter = new IntentFilter(BluetoothDevice.ACTION_FOUND);

this.registerReceiver(mReceiver, ifilter);

}

private class SingBroadcastReceiver extends BroadcastReceiver {

public void onReceive(Context context, Intent intent) {

String action = intent.getAction(); //may need to chain this to a recognizing function

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

// Get the BluetoothDevice object from the Intent

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

// Add the name and address to an array adapter to show in a Toast

String derp = device.getName() + " - " + device.getAddress();

Toast.makeText(context, derp, Toast.LENGTH_LONG);

}

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值