当前位置:   article > 正文

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

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);

}

}

}

}

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/AllinToyou/article/detail/483834
推荐阅读
相关标签
  

闽ICP备14008679号