Android蓝牙的开启-搜索-关闭演示

package com.example.demo;

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.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity implements OnClickListener
{
private TextView tv;
private Button start, end, search;
private BluetoothAdapter adapter;

@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView) findViewById(R.id.textView);
start = (Button) findViewById(R.id.start);
end = (Button) findViewById(R.id.end);
search = (Button) findViewById(R.id.search);

start.setOnClickListener(this);
end.setOnClickListener(this);
search.setOnClickListener(this);

//获取蓝牙适配器的实例
adapter = BluetoothAdapter.getDefaultAdapter();
//定义一个数据集,用来存储先有以有的蓝牙设备列表
Set device = adapter.getBondedDevices();
//如果有
if (device.size() > 0)
{
//遍历集合,添加到列表
for (BluetoothDevice bluetoothDevice : device)
{
tv.setText(bluetoothDevice.getName() + ","
+ bluetoothDevice.getAddress());
}
}

//注册正在搜索蓝牙时发送的广播
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(receiver, filter);

//注册搜索完成后发送的广播
filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
registerReceiver(receiver, filter);
}

private BroadcastReceiver receiver = new BroadcastReceiver()
{
@Override
public void onReceive(Context context, Intent intent)
{
String action = intent.getAction();
// 如果找到了设备
if (BluetoothDevice.ACTION_FOUND.equals(action))
{
BluetoothDevice device = intent
.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// 判断配对,如果没有配对,就添加到列表
if (device.getBondState() != BluetoothDevice.BOND_BONDED)
{
tv.append(device.getName() + ":" + device.getAddress());
}
//如果搜索完成
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED
.equals(action))
{
setTitle("扫描完成");
}
}
};

@Override
public void onClick(View v)
{
switch (v.getId())
{
case R.id.start://静默开启蓝牙
adapter.enable();
break;

case R.id.search://扫描蓝牙
setTitle("正在扫描...");
// 如果正在搜索(扫描只能执行一次,如果蓝牙正在扫描,又执行了一次扫描,会报错)
if (adapter.isDiscovering())
{
// 就取消
adapter.cancelDiscovery();
}
// 开启蓝牙搜索,此函数是运行在子线程中的
adapter.startDiscovery();
break;

case R.id.end://静默关闭
adapter.disable();
break;

default:
break;
}
}
}

你可能感兴趣的:(android)