小记BT配对及取消配对的应用程序源码,直接附上源码。
layout/activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.bttest.MainActivity" >
<TextView android:id="@+id/title_paired_devices"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/title_paired_devices"
android:visibility="gone"
android:background="#666"
android:textColor="#fff"
android:paddingLeft="5dp"
/>
<ListView android:id="@+id/paired_devices"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:transcriptMode="alwaysScroll"
android:layout_weight="1"
/>
<TextView android:id="@+id/title_new_devices"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/title_other_devices"
android:visibility="gone"
android:background="#666"
android:textColor="#fff"
android:paddingLeft="5dp"
/>
<ListView android:id="@+id/new_devices"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:transcriptMode="alwaysScroll"
/>
</LinearLayout>
layout/device_name.xml
<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright (C) 2009 The Android Open Source Project
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="18sp"
android:padding="5dp"
/>menu/main.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context="com.example.bttest.MainActivity" >
<item android:id="@+id/scan_paired"
android:icon="@android:drawable/ic_menu_search"
android:title="@string/scan_paired"
android:showAsAction="ifRoom|withText" />
<item android:id="@+id/scan_new"
android:icon="@android:drawable/ic_menu_mylocation"
android:title="@string/scan_new"
android:showAsAction="ifRoom|withText" />
</menu>values/strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">BtTest</string>
<string name="scan_paired">已配对的蓝牙设备</string>
<string name="none_found">No devices found</string>
<string name="scan_new">扫描新的蓝牙设备</string>
<string name="title_other_devices">Other Available Devices(click to pair)</string>
<string name="title_paired_devices">Paired Devices(click to unpair)</string>
<string name="bt_not_enabled_leaving">Bluetooth was not enabled!</string>
</resources>MainActivity.java
package com.example.bttest;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Iterator;
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.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity {
private ArrayAdapter<String> mPairedDevicesArrayAdapter;
private ArrayAdapter<String> mNewDevicesArrayAdapter;
private BluetoothAdapter adapter;
private static boolean clear_bt = false;
private HashMap<String, BluetoothDevice> NewBtInfo = new HashMap<String, BluetoothDevice>();
private HashMap<String, BluetoothDevice> PairedBtInfo = new HashMap<String, BluetoothDevice>();
private static final int REQUEST_ENABLE_BT = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
adapter = BluetoothAdapter.getDefaultAdapter();
// If the adapter is null, then Bluetooth is not supported
if (adapter == null) {
Toast.makeText(this, "Bluetooth is not available",
Toast.LENGTH_LONG).show();
finish();
return;
}
mPairedDevicesArrayAdapter = new ArrayAdapter<String>(this,
R.layout.device_name);
ListView pairedListView = (ListView) findViewById(R.id.paired_devices);
pairedListView.setAdapter(mPairedDevicesArrayAdapter);
pairedListView.setOnItemClickListener(mDeviceUnpairListener);
mNewDevicesArrayAdapter = new ArrayAdapter<String>(this,
R.layout.device_name);
ListView newDevicesListView = (ListView) findViewById(R.id.new_devices);
newDevicesListView.setAdapter(mNewDevicesArrayAdapter);
newDevicesListView.setOnItemClickListener(mDevicePairListener);
IntentFilter filter = new IntentFilter();
filter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
filter.addAction(BluetoothDevice.ACTION_FOUND);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
registerReceiver(mReceiver, filter);
// 调用isEnabled()方法判断当前蓝牙设备是否可用
if (!adapter.isEnabled()) {
// 如果蓝牙设备不可用的话,创建一个intent对象,该对象用于启动一个Activity,提示用户启动蓝牙适配器
Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(intent, REQUEST_ENABLE_BT);
}
}
// The on-click listener for all devices in the ListViews
private OnItemClickListener mDevicePairListener = new OnItemClickListener() {
public void onItemClick(AdapterView<?> av, View v, int arg2, long arg3) {
String BtDeviceName = mNewDevicesArrayAdapter.getItem(arg2);
BluetoothDevice BtDevice = NewBtInfo.get(BtDeviceName);
try {
// 开始配对,调用BluetoothDevice 的createBond()方法??
Method m = BtDevice.getClass().getMethod("createBond",
(Class[]) null);
m.invoke(BtDevice, (Object[]) null);
} catch (Throwable e) {
Log.e("BTtest", "", e);
}
}
};
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case REQUEST_ENABLE_BT:
// When the request to enable Bluetooth returns
if (resultCode != Activity.RESULT_OK) {
// User did not enable Bluetooth or an error occurred
Toast.makeText(this, R.string.bt_not_enabled_leaving,
Toast.LENGTH_SHORT).show();
finish();
break;
}
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.scan_paired) {
scan_paired_bt();
return true;
}
if (id == R.id.scan_new) {
doDiscovery();
return true;
}
return super.onOptionsItemSelected(item);
}
private void scan_paired_bt() {
findViewById(R.id.title_paired_devices).setVisibility(View.VISIBLE);
System.out.println("本机拥有蓝牙设备");
mPairedDevicesArrayAdapter.clear();
PairedBtInfo.clear();
// 得到所有已经配对的蓝牙适配器对象
Set<BluetoothDevice> devices = adapter.getBondedDevices();
if (devices.size() > 0) {
// 用迭代
for (Iterator<BluetoothDevice> iterator = devices.iterator(); iterator
.hasNext();) {
// 得到BluetoothDevice对象,也就是说得到配对的蓝牙适配器
BluetoothDevice device = (BluetoothDevice) iterator.next();
mPairedDevicesArrayAdapter.add(device.getName());
PairedBtInfo.put(device.getName(), device);
}
}
}
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)) {
if (clear_bt) {
mNewDevicesArrayAdapter.clear();
NewBtInfo.clear();
clear_bt = false;
}
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());
NewBtInfo.put(device.getName(), device);
}
// When discovery is finished, change the Activity title
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED
.equals(action)) {
if (mNewDevicesArrayAdapter.getCount() == 0) {
String noDevices = getResources().getText(
R.string.none_found).toString();
mNewDevicesArrayAdapter.add(noDevices);
}
} else if (BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)) {
scan_paired_bt();
}
}
};
private void doDiscovery() {
// Turn on sub-title for new devices
findViewById(R.id.title_new_devices).setVisibility(View.VISIBLE);
// If we're already discovering, stop it
if (adapter.isDiscovering()) {
adapter.cancelDiscovery();
}
if (!clear_bt) {
clear_bt = true;
}
// Request discover from BluetoothAdapter
adapter.startDiscovery();
}
// The on-click listener for all devices in the ListViews
private OnItemClickListener mDeviceUnpairListener = new OnItemClickListener() {
public void onItemClick(AdapterView<?> av, View v, int arg2, long arg3) {
String BtDeviceName = mPairedDevicesArrayAdapter.getItem(arg2);
BluetoothDevice BtDevice = PairedBtInfo.get(BtDeviceName);
unpairDevice(BtDevice);
}
};
private void unpairDevice(BluetoothDevice device) {
try {
Method m = device.getClass()
.getMethod("removeBond", (Class[]) null);
m.invoke(device, (Object[]) null);
} catch (Exception e) {
Log.e("unpair", e.getMessage());
}
}
}
本文提供了一段关于蓝牙(BT)设备配对和取消配对的应用程序源码,包括了对应的布局文件activity_main.xml和device_name.xml。

2万+

被折叠的 条评论
为什么被折叠?



