蓝牙Dome
1.编辑BlueToothTestActivity.java
package com.wang;
import java.util.ArrayList;
import java.util.List;
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.widget.Toast;
public class BlueToothTestActivity extends Activity {
//取得默认 的蓝牙适配器
private BluetoothAdapter bluetoothAdapter=BluetoothAdapter.getDefaultAdapter();
//存储收索到的可连接的设备
private List<BluetoothDevice> devices=new ArrayList<BluetoothDevice>();
private int REQUEST_ENABLE_BT=1;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
/*
* 检测蓝牙适配器工作是否正常,异常的时候提示用户
* 检测拦也适配器是否开启,没有这开启
*
* */
if (bluetoothAdapter==null) {
showToast("请检查你的蓝牙模块设别是否正常");
finish();
} else if(!bluetoothAdapter.isEnabled()){
Intent enableIntent=new Intent(bluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
}
}
//开始收索
private void doDiscovery(){
bluetoothAdapter.startDiscovery();
}
protected void onstart()
{
super.onStart();
Intent discoverIntent=new Intent(bluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
//开启收索可见模式,最大时间为300秒
discoverIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
startActivity(discoverIntent);
//ACTION_DISCOVERY_FINISHED结束收索远程设备
IntentFilter discoverFilter=new IntentFilter(bluetoothAdapter.ACTION_DISCOVERY_FINISHED);
registerReceiver(discovery_R, discoverFilter);
IntentFilter fouFilter=new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(found_R, fouFilter);
doDiscovery();
}
private void showToast(String string) {
Toast.makeText(BlueToothTestActivity.this, string, Toast.LENGTH_LONG).show();
}
protected void onDestroy() {
if (bluetoothAdapter!=null) {
bluetoothAdapter.cancelDiscovery();
bluetoothAdapter.disable();
}
super.onDestroy();
}
private void addpaired() {
Set<BluetoothDevice> parieDevices=bluetoothAdapter.getBondedDevices();
if (parieDevices.size()>0) {
for (BluetoothDevice device: parieDevices) {
devices.add(device);
}
}
}
//广播接收者 :当搜索到设备时候调用
BroadcastReceiver found_R=new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
BluetoothDevice device=intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
//将结果添加到列表中
devices.add(device);
}
};
//广播接收者 :当搜索结束的时候调用
BroadcastReceiver discovery_R=new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// 在停止收索后,追加配对的设备
addpaired();
//卸载注册的接受器
unregisterReceiver(found_R);
unregisterReceiver(this);
}
};
}
2.亲!别忘了设置权限哦!
<!-- 蓝牙操作权限 -->
<uses-permission
android:name="android.permission.BLUETOOTH_ADMIN"
/>
<!--蓝牙使用权限 -->
<uses-permission
android:name="android.permission.BLUETOOTH"
/>
3.由于模拟器没有蓝牙设备所以运行没成功,但是在自己手机上运行成功了: