问题描述
我想要探索蓝牙
的范围内,列表中的设备并与之配对,以他们的点击。我用下面的code,但它只是关闭应用程序,当我点击我要配对设备的名称。
我想知道错在我的code或任何其他方式做我所需要的。
包com.marakana;
进口java.util.Set中;
进口android.app.Activity;
进口android.bluetooth.BluetoothAdapter;
进口android.bluetooth.BluetoothDevice;
进口android.content.BroadcastReceiver;
进口android.content.Context;
进口android.content.Intent;
进口android.content.IntentFilter;
进口android.os.Bundle;
进口android.util.Log;
进口android.view.View;
进口android.view.Window;
进口android.view.View.OnClickListener;
进口android.widget.AdapterView;
进口android.widget.ArrayAdapter;
进口android.widget.Button;
进口android.widget.ListView;
进口android.widget.TextView;
进口android.widget.AdapterView.OnItemClickListener;
公共类扩展的BluetoothDemo活动{
// 调试
私有静态最后字符串变量=DeviceListActivity;
私有静态最终布尔D =真;
//返回意向额外
公共静态字符串EXTRA_DEVICE_ADDRESS =DEVICE_ADDRESS;
//会员领域
私人BluetoothAdapter mBtAdapter;
私人ArrayAdapter<字符串> mPairedDevicesArrayAdapter;
私人ArrayAdapter<字符串> mNewDevicesArrayAdapter;
@覆盖
保护无效的onCreate(包savedInstanceState){
super.onCreate(savedInstanceState);
//设置窗口
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
的setContentView(R.layout.device_list);
//设置结果取消了柜面用户备份出来
的setResult(Activity.RESULT_CANCELED);
//初始化按钮执行设备发现
按钮scanButton =(按钮)findViewById(R.id.button_scan);
scanButton.setOnClickListener(新OnClickListener(){
公共无效的onClick(视图v){
doDiscovery();
v.setVisibility(View.GONE);
}
});
//初始化数组适配器。一对已经配对的设备和
//一个用于新发现的设备
mPairedDevicesArrayAdapter =新的ArrayAdapter<字符串>(这一点,R.layout.device_name);
mNewDevicesArrayAdapter =新的ArrayAdapter<字符串>(这一点,R.layout.device_name);
//查找并设置ListView控件的配对设备
ListView控件pairedListView =(ListView控件)findViewById(R.id.paired_devices);
pairedListView.setAdapter(mPairedDevicesArrayAdapter);
pairedListView.setOnItemClickListener(mDeviceClickListener);
//查找和设置的ListView为新发现的设备
ListView控件newDevicesListView =(ListView控件)findViewById(R.id.new_devices);
newDevicesListView.setAdapter(mNewDevicesArrayAdapter);
newDevicesListView.setOnItemClickListener(mDeviceClickListener);
//注册的广播时,设备被发现
IntentFilter的过滤器=新的IntentFilter(BluetoothDevice.ACTION_FOUND);
this.registerReceiver(mReceiver,过滤器);
//注册的广播时,发现已完成
过滤器=新的IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
this.registerReceiver(mReceiver,过滤器);
//获取本地蓝牙适配器
mBtAdapter = BluetoothAdapter.getDefaultAdapter();
//获取一组当前配对设备
设置< BluetoothDevice类> pairedDevices = mBtAdapter.getBondedDevices();
//如果有配对的设备,每一个都添加到一个ArrayAdapter
如果(pairedDevices.size()大于0){
findViewById(R.id.title_paired_devices).setVisibility(View.VISIBLE);
对于(BluetoothDevice类设备:pairedDevices){
mPairedDevicesArrayAdapter.add(device.getName()+\ N+ device.getAddress());
}
} 其他 {
。字符串nodevices选项= getResources()的getText(R.string.none_paired)的ToString();
mPairedDevicesArrayAdapter.add(nodevices选项);
}
}
@覆盖
保护无效的onDestroy(){
super.onDestroy();
//确保我们没有做发现了
如果(mBtAdapter!= NULL){
mBtAdapter.cancelDiscovery();
}
//注销广播监听器
this.unregisterReceiver(mReceiver);
}
/ **
*启动设备发现与BluetoothAdapter
* /
私人无效doDiscovery(){
如果(D)的Log.d(TAG,doDiscovery());
//指示扫描标题
setProgressBarIndeterminateVisibility(真正的);
的setTitle(R.string.scanning);
//开启副标题为新设备
findViewById(R.id.title_new_devices).setVisibility(View.VISIBLE);
//如果我们已经发现,阻止它
如果(mBtAdapter.isDiscovering()){
mBtAdapter.cancelDiscovery();
}
//请求从BluetoothAdapter发现
mBtAdapter.startDiscovery();
}
//上单击侦听器的列表视图的所有设备
私人OnItemClickListener mDeviceClickListener =新OnItemClickListener(){
公共无效onItemClick(适配器视图<> AV,视图V,INT ARG2,长ARG3){
//取消的发现,因为它是昂贵的,我们将要连接
mBtAdapter.cancelDiscovery();
//获取设备的MAC地址,这是过去17个字符的视图
字符串信息=((TextView中)V).getText()的toString()。
字符串的地址= info.substring(info.length() - 17);
//创建结果意向,包括MAC地址
意向意图=新的意图();
intent.putExtra(EXTRA_DEVICE_ADDRESS,地址);
//设置结果,并完成这个活动
的setResult(Activity.RESULT_OK,意图);
完();
}
};
//监听发现的设备和BroadcastReceiver的
//当发现完成改变标题
私人最终的BroadcastReceiver mReceiver =新的BroadcastReceiver(){
@覆盖
公共无效的onReceive(上下文的背景下,意图意图){
串动= intent.getAction();
//当发现找到的设备
如果(BluetoothDevice.ACTION_FOUND.equals(动作)){
//从意图获取BluetoothDevice类对象
BluetoothDevice类设备= intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
//如果它已经配对,跳过它,因为它已经上市已经
如果(device.getBondState()!= BluetoothDevice.BOND_BONDED){
mNewDevicesArrayAdapter.add(device.getName()+\ N+ device.getAddress());
}
//当发现完成后,修改活动名称
}否则如果(BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(动作)){
setProgressBarIndeterminateVisibility(假);
的setTitle(R.string.select_device);
如果(mNewDevicesArrayAdapter.getCount()== 0){
。字符串nodevices选项= getResources()的getText(R.string.none_found)的ToString();
mNewDevicesArrayAdapter.add(nodevices选项);
}
}
}
};
}
在我的第一个回答的逻辑见谁想要去的逻辑而已。
我想我是不是能明确为@ chalukya3545,这就是为什么我添加了整个code,让他知道的code确切的流量。
BluetoothDemo.java
公共类扩展的BluetoothDemo活动{
ListView控件listViewPaired;
ListView控件listViewDetected;
ArrayList的<字符串> arrayListpaired;
按钮buttonSearch,buttonOn,buttonDesc,buttonOff;
ArrayAdapter<字符串>适配器,detectedAdapter;
静态HandleSeacrh handleSeacrh;
BluetoothDevice类bdDevice;
BluetoothClass bdClass;
ArrayList的< BluetoothDevice类> arrayListPairedBluetoothDevices;
私人ButtonClicked点击;
ListItemClickedonPaired listItemClickedonPaired;
BluetoothAdapter bluetoothAdapter = NULL;
ArrayList的< BluetoothDevice类> arrayListBluetoothDevices = NULL;
ListItemClicked listItemClicked;
@覆盖
公共无效的onCreate(包savedInstanceState){
super.onCreate(savedInstanceState);
的setContentView(R.layout.main);
listViewDetected =(ListView控件)findViewById(R.id.listViewDetected);
listViewPaired =(ListView控件)findViewById(R.id.listViewPaired);
buttonSearch =(按钮)findViewById(R.id.buttonSearch);
buttonOn =(按钮)findViewById(R.id.buttonOn);
buttonDesc =(按钮)findViewById(R.id.buttonDesc);
buttonOff =(按钮)findViewById(R.id.buttonOff);
arrayListpaired =新的ArrayList<字符串>();
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
点击=新ButtonClicked();
handleSeacrh =新HandleSeacrh();
arrayListPairedBluetoothDevices =新的ArrayList< BluetoothDevice类>();
/ *
*上述声明只是为了让已配对的蓝牙设备;
*这有助于去除配对设备之间的纽带。
* /
listItemClickedonPaired =新ListItemClickedonPaired();
arrayListBluetoothDevices =新的ArrayList< BluetoothDevice类>();
适配器=新的ArrayAdapter<字符串>(BluetoothDemo.this,android.R.layout.simple_list_item_1,arrayListpaired);
detectedAdapter =新的ArrayAdapter<字符串>(BluetoothDemo.this,android.R.layout.simple_list_item_single_choice);
listViewDetected.setAdapter(detectedAdapter);
listItemClicked =新ListItemClicked();
detectedAdapter.notifyDataSetChanged();
listViewPaired.setAdapter(适配器);
}
@覆盖
保护无效的OnStart(){
// TODO自动生成方法存根
super.onStart();
getPairedDevices();
buttonOn.setOnClickListener(点击);
buttonSearch.setOnClickListener(点击);
buttonDesc.setOnClickListener(点击);
buttonOff.setOnClickListener(点击);
listViewDetected.setOnItemClickListener(listItemClicked);
listViewPaired.setOnItemClickListener(listItemClickedonPaired);
}
私人无效getPairedDevices(){
设置< BluetoothDevice类> pairedDevice = bluetoothAdapter.getBondedDevices();
如果(pairedDevice.size()大于0)
{
对于(BluetoothDevice类设备:pairedDevice)
{
arrayListpaired.add(device.getName()+\ N+ device.getAddress());
arrayListPairedBluetoothDevices.add(设备);
}
}
adapter.notifyDataSetChanged();
}
类ListItemClicked实现OnItemClickListener
{
@覆盖
公共无效onItemClick(适配器视图<>母公司视图中查看,INT位置,长的id){
// TODO自动生成方法存根
bdDevice = arrayListBluetoothDevices.get(位置);
// bdClass = arrayListBluetoothDevices.get(位置);
Log.i(日志,该DVICE:+ bdDevice.toString());
/ *
*下面在这里我们可以做配对无需调用callthread(),我们可以直接调用
*连接()。但对于安全方面,我们必须usethe线程对象。
* /
// callThread();
//连接(bdDevice);
布尔isBonded = FALSE;
尝试 {
isBonded = createBond(bdDevice);
如果(isBonded)
{
//arrayListpaired.add(bdDevice.getName()+\ N+ bdDevice.getAddress());
//adapter.notifyDataSetChanged();
getPairedDevices();
adapter.notifyDataSetChanged();
}
}赶上(例外五){
e.printStackTrace();
} //连接(bdDevice);
Log.i(日志,债券被创建:+ isBonded);
}
}
类ListItemClickedonPaired实现OnItemClickListener
{
@覆盖
公共无效onItemClick(适配器视图<>母公司视图中查看,INT位置,长的id){
bdDevice = arrayListPairedBluetoothDevices.get(位置);
尝试 {
布尔removeBonding = removeBond(bdDevice);
如果(removeBonding)
{
arrayListpaired.remove(位置);
adapter.notifyDataSetChanged();
}
Log.i(日志,删除+ removeBonding);
}赶上(例外五){
// TODO自动生成的catch块
e.printStackTrace();
}
}
}
/ *私人无效callThread(){
新的Thread(){
公共无效的run(){
布尔isBonded = FALSE;
尝试 {
isBonded = createBond(bdDevice);
如果(isBonded)
{
arrayListpaired.add(bdDevice.getName()+\ N+ bdDevice.getAddress());
adapter.notifyDataSetChanged();
}
}赶上(例外五){
// TODO自动生成的catch块
e.printStackTrace();
} //连接(bdDevice);
Log.i(日志,债券被创建:+ isBonded);
}
}。开始();
} * /
私人布尔连接(BluetoothDevice类bdDevice){
布尔布尔=假;
尝试 {
Log.i(日志,服务方法被称为);
类的cl =的Class.forName(android.bluetooth.BluetoothDevice);
类[]面值= {};
方法方法= cl.getMethod(createBond,标准杆);
[对象]的args = {};
布尔=(布尔)method.invoke(bdDevice); //参数); //这个调用创建配对检测到的设备。
//Log.i("Log,这是:+ bool.booleanValue());
//Log.i("Log,devicesss:+ bdDevice.getName());
}赶上(例外五){
Log.i(日志,内部serviceFromDevice法捕);
e.printStackTrace();
}
返回bool.booleanValue();
};
公共布尔removeBond(BluetoothDevice类btDevice)
抛出异常
{
类btClass =的Class.forName(android.bluetooth.BluetoothDevice);
方法removeBondMethod = btClass.getMethod(removeBond);
布尔的returnValue =(布尔)removeBondMethod.invoke(btDevice);
返回returnValue.booleanValue();
}
公共布尔createBond(BluetoothDevice类btDevice)
抛出异常
{
类class1 =的Class.forName(android.bluetooth.BluetoothDevice);
方法createBondMethod = class1.getMethod(createBond);
布尔的returnValue =(布尔)createBondMethod.invoke(btDevice);
返回returnValue.booleanValue();
}
类ButtonClicked工具OnClickListener
{
@覆盖
公共无效的onClick(视图查看){
开关(view.getId()){
案例R.id.buttonOn:
onBluetooth();
打破;
案例R.id.buttonSearch:
arrayListBluetoothDevices.clear();
startSearching();
打破;
案例R.id.buttonDesc:
makeDiscoverable();
打破;
案例R.id.buttonOff:
offBluetooth();
打破;
默认:
打破;
}
}
}
私人的BroadcastReceiver myReceiver =新的BroadcastReceiver(){
@覆盖
公共无效的onReceive(上下文的背景下,意图意图){
消息味精= Message.obtain();
串动= intent.getAction();
如果(BluetoothDevice.ACTION_FOUND.equals(动作)){
Toast.makeText(上下文中,ACTION_FOUND,Toast.LENGTH_SHORT).show();
BluetoothDevice类设备= intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
尝试
{
//device.getClass().getMethod("setPairingConfirmation,boolean.class).invoke(设备,真正的);
//device.getClass().getMethod("cancelPairingUserInput,boolean.class).invoke(设备);
}
赶上(例外五){
Log.i(日志,内部异常:);
e.printStackTrace();
}
如果(arrayListBluetoothDevices.size()。1)//这个检查是否蓝牙设备的大小为0,然后添加
{//设备到ArrayList。
detectedAdapter.add(device.getName()+\ N+ device.getAddress());
arrayListBluetoothDevices.add(设备);
detectedAdapter.notifyDataSetChanged();
}
其他
{
布尔标志= TRUE; //标志,以指示该特定设备已在arlist或不
的for(int i = 0; I< arrayListBluetoothDevices.size();我++)
{
如果(device.getAddress()。等于(arrayListBluetoothDevices.get(ⅰ).getAddress()))
{
标志= FALSE;
}
}
如果(旗==真)
{
detectedAdapter.add(device.getName()+\ N+ device.getAddress());
arrayListBluetoothDevices.add(设备);
detectedAdapter.notifyDataSetChanged();
}
}
}
}
};
私人无效startSearching(){
Log.i(在开始搜索法,日志,);
IntentFilter的IntentFilter的=新的IntentFilter(BluetoothDevice.ACTION_FOUND);
BluetoothDemo.this.registerReceiver(myReceiver,IntentFilter的);
bluetoothAdapter.startDiscovery();
}
私人无效onBluetooth(){
如果(!bluetoothAdapter.isEnabled())
{
bluetoothAdapter.enable();
Log.i(日志,蓝牙已启用);
}
}
私人无效offBluetooth(){
如果(bluetoothAdapter.isEnabled())
{
bluetoothAdapter.disable();
}
}
私人无效makeDiscoverable(){
意图discoverableIntent =新的意图(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION,300);
startActivity(discoverableIntent);
Log.i(日志,可发现);
}
类HandleSeacrh扩展了Handler
{
@覆盖
公共无效的handleMessage(信息MSG){
开关(msg.what){
案例111:
打破;
默认:
打破;
}
}
}
}
下面是的main.xml
< XML版本=1.0编码=UTF-8&GT?;
< LinearLayout中的xmlns:机器人=http://schemas.android.com/apk/res/android
机器人:layout_width =FILL_PARENT
机器人:layout_height =FILL_PARENT
机器人:方向=垂直>
<按钮
机器人:ID =@ + ID / buttonOn
机器人:layout_width =match_parent
机器人:layout_height =WRAP_CONTENT
机器人:文本=开/>
<按钮
机器人:ID =@ + ID / buttonDesc
机器人:layout_width =FILL_PARENT
机器人:layout_height =WRAP_CONTENT
机器人:文本=使可见/>
<按钮
机器人:ID =@ + ID / buttonSearch
机器人:layout_width =match_parent
机器人:layout_height =WRAP_CONTENT
机器人:文本=搜索/>
<按钮
机器人:ID =@ + ID / buttonOff
机器人:layout_width =match_parent
机器人:layout_height =WRAP_CONTENT
机器人:文本=蓝牙关/>
<的ListView
机器人:ID =@ + ID / listViewPaired
机器人:layout_width =match_parent
机器人:layout_height =120dp>
< / ListView控件>
<的ListView
机器人:ID =@ + ID / listViewDetected
机器人:layout_width =match_parent
机器人:layout_height =match_parent>
< / ListView控件>
< / LinearLayout中>
将此权限您的 AndroidManifest.xml中文件:
<使用-权限的Android:名称=android.permission.BLUETOOTH_ADMIN/>
<使用-权限的Android:名称=android.permission.BLUETOOTH/>
I want to discover bluetooth
devices in range, list and pair to them on click. I used following code but its just closing application when I click on device name which I want to pair.
I want to know mistake in my code or any other way to do what i need.
package com.marakana;
import java.util.Set;
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.util.Log;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
public class BluetoothDemo extends Activity {
// Debugging
private static final String TAG = "DeviceListActivity";
private static final boolean D = true;
// Return Intent extra
public static String EXTRA_DEVICE_ADDRESS = "device_address";
// Member fields
private BluetoothAdapter mBtAdapter;
private ArrayAdapter<String> mPairedDevicesArrayAdapter;
private ArrayAdapter<String> mNewDevicesArrayAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Setup the window
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.device_list);
// Set result CANCELED incase the user backs out
setResult(Activity.RESULT_CANCELED);
// Initialize the button to perform device discovery
Button scanButton = (Button) findViewById(R.id.button_scan);
scanButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
doDiscovery();
v.setVisibility(View.GONE);
}
});
// Initialize array adapters. One for already paired devices and
// one for newly discovered devices
mPairedDevicesArrayAdapter = new ArrayAdapter<String>(this, R.layout.device_name);
mNewDevicesArrayAdapter = new ArrayAdapter<String>(this, R.layout.device_name);
// Find and set up the ListView for paired devices
ListView pairedListView = (ListView) findViewById(R.id.paired_devices);
pairedListView.setAdapter(mPairedDevicesArrayAdapter);
pairedListView.setOnItemClickListener(mDeviceClickListener);
// Find and set up the ListView for newly discovered devices
ListView newDevicesListView = (ListView) findViewById(R.id.new_devices);
newDevicesListView.setAdapter(mNewDevicesArrayAdapter);
newDevicesListView.setOnItemClickListener(mDeviceClickListener);
// Register for broadcasts when a device is discovered
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
this.registerReceiver(mReceiver, filter);
// Register for broadcasts when discovery has finished
filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
this.registerReceiver(mReceiver, filter);
// Get the local Bluetooth adapter
mBtAdapter = BluetoothAdapter.getDefaultAdapter();
// Get a set of currently paired devices
Set<BluetoothDevice> pairedDevices = mBtAdapter.getBondedDevices();
// If there are paired devices, add each one to the ArrayAdapter
if (pairedDevices.size() > 0) {
findViewById(R.id.title_paired_devices).setVisibility(View.VISIBLE);
for (BluetoothDevice device : pairedDevices) {
mPairedDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());
}
} else {
String noDevices = getResources().getText(R.string.none_paired).toString();
mPairedDevicesArrayAdapter.add(noDevices);
}
}
@Override
protected void onDestroy() {
super.onDestroy();
// Make sure we're not doing discovery anymore
if (mBtAdapter != null) {
mBtAdapter.cancelDiscovery();
}
// Unregister broadcast listeners
this.unregisterReceiver(mReceiver);
}
/**
* Start device discover with the BluetoothAdapter
*/
private void doDiscovery() {
if (D) Log.d(TAG, "doDiscovery()");
// Indicate scanning in the title
setProgressBarIndeterminateVisibility(true);
setTitle(R.string.scanning);
// Turn on sub-title for new devices
findViewById(R.id.title_new_devices).setVisibility(View.VISIBLE);
// If we're already discovering, stop it
if (mBtAdapter.isDiscovering()) {
mBtAdapter.cancelDiscovery();
}
// Request discover from BluetoothAdapter
mBtAdapter.startDiscovery();
}
// The on-click listener for all devices in the ListViews
private OnItemClickListener mDeviceClickListener = new OnItemClickListener() {
public void onItemClick(AdapterView<?> av, View v, int arg2, long arg3) {
// Cancel discovery because it's costly and we're about to connect
mBtAdapter.cancelDiscovery();
// Get the device MAC address, which is the last 17 chars in the View
String info = ((TextView) v).getText().toString();
String address = info.substring(info.length() - 17);
// Create the result Intent and include the MAC address
Intent intent = new Intent();
intent.putExtra(EXTRA_DEVICE_ADDRESS, address);
// Set result and finish this Activity
setResult(Activity.RESULT_OK, intent);
finish();
}
};
// The BroadcastReceiver that listens for discovered devices and
// changes the title when discovery is finished
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
// When discovery finds a device
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// Get the BluetoothDevice object from the Intent
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// If it's already paired, skip it, because it's been listed already
if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
mNewDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());
}
// When discovery is finished, change the Activity title
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
setProgressBarIndeterminateVisibility(false);
setTitle(R.string.select_device);
if (mNewDevicesArrayAdapter.getCount() == 0) {
String noDevices = getResources().getText(R.string.none_found).toString();
mNewDevicesArrayAdapter.add(noDevices);
}
}
}
};
}
In my first answer the logic is shown for those who want to go with the logic only.
I think I was not able to make clear to @chalukya3545, that's why I am adding the whole code to let him know the exact flow of the code.
BluetoothDemo.java
public class BluetoothDemo extends Activity {
ListView listViewPaired;
ListView listViewDetected;
ArrayList<String> arrayListpaired;
Button buttonSearch,buttonOn,buttonDesc,buttonOff;
ArrayAdapter<String> adapter,detectedAdapter;
static HandleSeacrh handleSeacrh;
BluetoothDevice bdDevice;
BluetoothClass bdClass;
ArrayList<BluetoothDevice> arrayListPairedBluetoothDevices;
private ButtonClicked clicked;
ListItemClickedonPaired listItemClickedonPaired;
BluetoothAdapter bluetoothAdapter = null;
ArrayList<BluetoothDevice> arrayListBluetoothDevices = null;
ListItemClicked listItemClicked;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
listViewDetected = (ListView) findViewById(R.id.listViewDetected);
listViewPaired = (ListView) findViewById(R.id.listViewPaired);
buttonSearch = (Button) findViewById(R.id.buttonSearch);
buttonOn = (Button) findViewById(R.id.buttonOn);
buttonDesc = (Button) findViewById(R.id.buttonDesc);
buttonOff = (Button) findViewById(R.id.buttonOff);
arrayListpaired = new ArrayList<String>();
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
clicked = new ButtonClicked();
handleSeacrh = new HandleSeacrh();
arrayListPairedBluetoothDevices = new ArrayList<BluetoothDevice>();
/*
* the above declaration is just for getting the paired bluetooth devices;
* this helps in the removing the bond between paired devices.
*/
listItemClickedonPaired = new ListItemClickedonPaired();
arrayListBluetoothDevices = new ArrayList<BluetoothDevice>();
adapter= new ArrayAdapter<String>(BluetoothDemo.this, android.R.layout.simple_list_item_1, arrayListpaired);
detectedAdapter = new ArrayAdapter<String>(BluetoothDemo.this, android.R.layout.simple_list_item_single_choice);
listViewDetected.setAdapter(detectedAdapter);
listItemClicked = new ListItemClicked();
detectedAdapter.notifyDataSetChanged();
listViewPaired.setAdapter(adapter);
}
@Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
getPairedDevices();
buttonOn.setOnClickListener(clicked);
buttonSearch.setOnClickListener(clicked);
buttonDesc.setOnClickListener(clicked);
buttonOff.setOnClickListener(clicked);
listViewDetected.setOnItemClickListener(listItemClicked);
listViewPaired.setOnItemClickListener(listItemClickedonPaired);
}
private void getPairedDevices() {
Set<BluetoothDevice> pairedDevice = bluetoothAdapter.getBondedDevices();
if(pairedDevice.size()>0)
{
for(BluetoothDevice device : pairedDevice)
{
arrayListpaired.add(device.getName()+"\n"+device.getAddress());
arrayListPairedBluetoothDevices.add(device);
}
}
adapter.notifyDataSetChanged();
}
class ListItemClicked implements OnItemClickListener
{
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// TODO Auto-generated method stub
bdDevice = arrayListBluetoothDevices.get(position);
//bdClass = arrayListBluetoothDevices.get(position);
Log.i("Log", "The dvice : "+bdDevice.toString());
/*
* here below we can do pairing without calling the callthread(), we can directly call the
* connect(). but for the safer side we must usethe threading object.
*/
//callThread();
//connect(bdDevice);
Boolean isBonded = false;
try {
isBonded = createBond(bdDevice);
if(isBonded)
{
//arrayListpaired.add(bdDevice.getName()+"\n"+bdDevice.getAddress());
//adapter.notifyDataSetChanged();
getPairedDevices();
adapter.notifyDataSetChanged();
}
} catch (Exception e) {
e.printStackTrace();
}//connect(bdDevice);
Log.i("Log", "The bond is created: "+isBonded);
}
}
class ListItemClickedonPaired implements OnItemClickListener
{
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,long id) {
bdDevice = arrayListPairedBluetoothDevices.get(position);
try {
Boolean removeBonding = removeBond(bdDevice);
if(removeBonding)
{
arrayListpaired.remove(position);
adapter.notifyDataSetChanged();
}
Log.i("Log", "Removed"+removeBonding);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
/*private void callThread() {
new Thread(){
public void run() {
Boolean isBonded = false;
try {
isBonded = createBond(bdDevice);
if(isBonded)
{
arrayListpaired.add(bdDevice.getName()+"\n"+bdDevice.getAddress());
adapter.notifyDataSetChanged();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}//connect(bdDevice);
Log.i("Log", "The bond is created: "+isBonded);
}
}.start();
}*/
private Boolean connect(BluetoothDevice bdDevice) {
Boolean bool = false;
try {
Log.i("Log", "service method is called ");
Class cl = Class.forName("android.bluetooth.BluetoothDevice");
Class[] par = {};
Method method = cl.getMethod("createBond", par);
Object[] args = {};
bool = (Boolean) method.invoke(bdDevice);//, args);// this invoke creates the detected devices paired.
//Log.i("Log", "This is: "+bool.booleanValue());
//Log.i("Log", "devicesss: "+bdDevice.getName());
} catch (Exception e) {
Log.i("Log", "Inside catch of serviceFromDevice Method");
e.printStackTrace();
}
return bool.booleanValue();
};
public boolean removeBond(BluetoothDevice btDevice)
throws Exception
{
Class btClass = Class.forName("android.bluetooth.BluetoothDevice");
Method removeBondMethod = btClass.getMethod("removeBond");
Boolean returnValue = (Boolean) removeBondMethod.invoke(btDevice);
return returnValue.booleanValue();
}
public boolean createBond(BluetoothDevice btDevice)
throws Exception
{
Class class1 = Class.forName("android.bluetooth.BluetoothDevice");
Method createBondMethod = class1.getMethod("createBond");
Boolean returnValue = (Boolean) createBondMethod.invoke(btDevice);
return returnValue.booleanValue();
}
class ButtonClicked implements OnClickListener
{
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.buttonOn:
onBluetooth();
break;
case R.id.buttonSearch:
arrayListBluetoothDevices.clear();
startSearching();
break;
case R.id.buttonDesc:
makeDiscoverable();
break;
case R.id.buttonOff:
offBluetooth();
break;
default:
break;
}
}
}
private BroadcastReceiver myReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Message msg = Message.obtain();
String action = intent.getAction();
if(BluetoothDevice.ACTION_FOUND.equals(action)){
Toast.makeText(context, "ACTION_FOUND", Toast.LENGTH_SHORT).show();
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
try
{
//device.getClass().getMethod("setPairingConfirmation", boolean.class).invoke(device, true);
//device.getClass().getMethod("cancelPairingUserInput", boolean.class).invoke(device);
}
catch (Exception e) {
Log.i("Log", "Inside the exception: ");
e.printStackTrace();
}
if(arrayListBluetoothDevices.size()<1) // this checks if the size of bluetooth device is 0,then add the
{ // device to the arraylist.
detectedAdapter.add(device.getName()+"\n"+device.getAddress());
arrayListBluetoothDevices.add(device);
detectedAdapter.notifyDataSetChanged();
}
else
{
boolean flag = true; // flag to indicate that particular device is already in the arlist or not
for(int i = 0; i<arrayListBluetoothDevices.size();i++)
{
if(device.getAddress().equals(arrayListBluetoothDevices.get(i).getAddress()))
{
flag = false;
}
}
if(flag == true)
{
detectedAdapter.add(device.getName()+"\n"+device.getAddress());
arrayListBluetoothDevices.add(device);
detectedAdapter.notifyDataSetChanged();
}
}
}
}
};
private void startSearching() {
Log.i("Log", "in the start searching method");
IntentFilter intentFilter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
BluetoothDemo.this.registerReceiver(myReceiver, intentFilter);
bluetoothAdapter.startDiscovery();
}
private void onBluetooth() {
if(!bluetoothAdapter.isEnabled())
{
bluetoothAdapter.enable();
Log.i("Log", "Bluetooth is Enabled");
}
}
private void offBluetooth() {
if(bluetoothAdapter.isEnabled())
{
bluetoothAdapter.disable();
}
}
private void makeDiscoverable() {
Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
startActivity(discoverableIntent);
Log.i("Log", "Discoverable ");
}
class HandleSeacrh extends Handler
{
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case 111:
break;
default:
break;
}
}
}
}
Here is the main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<Button
android:id="@+id/buttonOn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="On"/>
<Button
android:id="@+id/buttonDesc"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Make Discoverable"/>
<Button
android:id="@+id/buttonSearch"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Search"/>
<Button
android:id="@+id/buttonOff"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Bluetooth Off"/>
<ListView
android:id="@+id/listViewPaired"
android:layout_width="match_parent"
android:layout_height="120dp">
</ListView>
<ListView
android:id="@+id/listViewDetected"
android:layout_width="match_parent"
android:layout_height="match_parent">
</ListView>
</LinearLayout>
Add this permissions to your AndroidManifest.xml file:
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.BLUETOOTH" />
The output for this code will look like this.
这篇关于安卓+对通过蓝牙编程装置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!