android Bluetooth 开发(二):打开、关闭、搜索、允许搜索、查看
相关项目的下载链接本项目:点击打开链接继本项目之后实现了语音识别:点击打开链接1.承接上一篇文章,本篇文章主要实现了蓝牙的打开 关闭 允许搜索 查看配对设备2. BluetoothInit,主要实现了部件的初始化,按钮的点击事件,通过ListVIew显示本地配对的蓝牙设备,ListView的点击事件,弹出对话框,作为客户端连接服务器package com.example.sacnbluetooth
·
相关项目的下载链接
本项目:点击打开链接
继本项目之后实现了语音识别:点击打开链接
1.承接上一篇文章,本篇文章主要实现了蓝牙的打开 关闭 允许搜索 查看配对设备
2. BluetoothInit,主要实现了部件的初始化,按钮的点击事件,通过ListVIew显示本地配对的蓝牙设备,ListView的点击事件,弹出对话框,作为客户端连接服务器
package com.example.sacnbluetooth;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
public class BluetoothInit extends AppCompatActivity implements View.OnClickListener,AdapterView.OnItemClickListener{
private static final String TAG = BluetoothInit.class.getSimpleName();
private BluetoothAdapter bluetoothAdapter = null;
private BluetoothDevice bluetoothDevice = null;
private Button openButton;
private Button closeButton;
private Button pairButton;
private Button discoverableButton;
private Button serviceButton;
private Button clientButton;
private ArrayAdapter<String> arrayAdapter;
private ListView deviceListview;
private List<String> deviceList = new ArrayList<String>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.init_layout);
initView();
initBluetooth();
}
private void initView(){
openButton = (Button) findViewById(R.id.open_bluetooth);
closeButton = (Button) findViewById(R.id.close_bluetooth);
pairButton = (Button) findViewById(R.id.pair_bluetooth);
discoverableButton = (Button) findViewById(R.id.discoverable_bluetooth);
serviceButton = (Button) findViewById(R.id.service_bluetooth);
clientButton = (Button) findViewById(R.id.client_bluetooth);
//设置Button监听事件
openButton.setOnClickListener(this);
closeButton.setOnClickListener(this);
pairButton.setOnClickListener(this);
discoverableButton.setOnClickListener(this);
serviceButton.setOnClickListener(this);
clientButton.setOnClickListener(this);
arrayAdapter = new ArrayAdapter<String>(BluetoothInit.this,
android.R.layout.simple_expandable_list_item_1,deviceList);
deviceListview = (ListView) findViewById(R.id.pair_devices_listview);
deviceListview.setAdapter(arrayAdapter);
deviceListview.setOnItemClickListener(this);//设置ListView监听事件
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
}
private void initBluetooth(){
if (bluetoothAdapter != null){
Log.d(TAG, "onClick: 设备支持蓝牙");
}else {
Log.d(TAG, "onClick: 无蓝牙设备");
return;
}
}
@Override//Button点击事件
public void onClick(View v) {
switch (v.getId()){
case R.id.open_bluetooth:
if (bluetoothAdapter.isEnabled()){
Log.d(TAG, "onClick: 已打开蓝牙");
Toast.makeText(BluetoothInit.this,"蓝牙已打开,请不要重复点击",Toast.LENGTH_SHORT).show();
deviceList.clear();//清空设备列表
arrayAdapter.notifyDataSetChanged();//更新
}else {
Log.d(TAG, "onClick: 正在打开蓝牙");
Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);//需要BLUETOOTH权限
startActivityForResult(intent,RESULT_OK);
deviceList.clear();//清空设备列表
arrayAdapter.notifyDataSetChanged();//更新
}
break;
case R.id.close_bluetooth:
if (bluetoothAdapter.isEnabled()){
Log.d(TAG, "onClick: 正在关闭蓝牙");
Toast.makeText(BluetoothInit.this,"蓝牙已关闭",Toast.LENGTH_SHORT).show();
bluetoothAdapter.disable();//需要BLUETOOTH_ADMIN权限
Log.d(TAG, "onClick: 蓝牙已关闭");
}else {
Log.d(TAG, "onClick: 蓝牙已关闭");
Toast.makeText(BluetoothInit.this,"蓝牙已关闭,请不要重复点击",Toast.LENGTH_SHORT).show();
}
break;
case R.id.pair_bluetooth:
if (bluetoothAdapter.isEnabled()){
Set<BluetoothDevice> devices = bluetoothAdapter.getBondedDevices();//得到本地蓝牙集合
deviceList.clear();
for (BluetoothDevice device:devices){
Log.d(TAG, "MainActivity: "+"名字:"+device.getName()+"\n地址:"+device.getAddress());//得到设备名字和地址
deviceList.add("名字:"+device.getName()+"\n地址:"+device.getAddress());
arrayAdapter.notifyDataSetChanged();//更新数据
}
}else {
Toast.makeText(BluetoothInit.this,"蓝牙未打开",Toast.LENGTH_SHORT).show();
}
break;
case R.id.discoverable_bluetooth:
Log.d(TAG, "onClick: 可被搜索");
Intent discoverable = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);//请求搜索
discoverable.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION,120);//可被搜索120s
startActivity(discoverable);//开始
break;
case R.id.service_bluetooth:
Log.d(TAG, "onClick: 服务端");
BluetoothMsg.serviceOrCilent = BluetoothMsg.ServerOrCilent.SERVICE;//决定是server还是client
Intent service = new Intent(BluetoothInit.this,SearchBluetoothDevice.class);
startActivity(service);
break;
case R.id.client_bluetooth:
Log.d(TAG, "onClick: 客户端");
BluetoothMsg.serviceOrCilent = BluetoothMsg.ServerOrCilent.CILENT;//决定是server还是client
Intent client = new Intent(BluetoothInit.this,SearchBluetoothDevice.class);
startActivity(client);
break;
}
}
@Override//ListView点击事件
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
final String message = deviceList.get(position);//得到标签信息
//创建一个对话框,并设置标题内容
AlertDialog.Builder dialog = new AlertDialog.Builder(BluetoothInit.this);
dialog.setTitle("确认连接");
dialog.setMessage(message);
//dialog.setCancelable(true);//进制返回键
dialog.setPositiveButton("连接", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
BluetoothMsg.serviceOrCilent = BluetoothMsg.ServerOrCilent.CILENT;
BluetoothMsg.BlueToothAddress = message.substring(message.length()-17);
if(BluetoothMsg.lastblueToothAddress!=BluetoothMsg.BlueToothAddress){
BluetoothMsg.lastblueToothAddress=BluetoothMsg.BlueToothAddress;
}
Intent intent = new Intent(BluetoothInit.this,BluetoothChat.class);
startActivity(intent);
}
});
dialog.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
return;
}
});
dialog.show();//显示
}
}
3.SearchBluetoothDevice从BluetoothInit的服务端 客户端 跳转的界面,从服务端跳转,本机便作为服务端,客户端如同,此界面会显示当前检测到的所有设备,包括配对的,为配对的,可分别实现配对设配的连接,未配对设备的配对
package com.example.sacnbluetooth;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.Toast;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
public class SearchBluetoothDevice extends AppCompatActivity implements AdapterView.OnItemClickListener{
private static final String TAG = SearchBluetoothDevice.class.getSimpleName();
private BluetoothAdapter bluetoothAdapter = null;
private Set<BluetoothDevice> setBluetoothDevice;
private BluetoothDevice bluetoothDevice;
private DiscoveryBluetoothBroadcast discoveryBroadcast;
private IntentFilter DiscoveryFilter;
private ProgressBar startBar;
private Button searchButton;
private ArrayAdapter<String> arrayAdapter;
private ListView deviceListView;
private List<String> deviceList = new ArrayList<String>();
private Boolean state = true;//新设配标志
private String message = "";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search_layout);
initView();
initBluetooth();
}
private void initView(){
startBar = (ProgressBar) findViewById(R.id.start_discovery_bar);
searchButton = (Button) findViewById(R.id.start_search_button);
searchButton.setOnClickListener(new searchButtonClick());
arrayAdapter = new ArrayAdapter<String>(SearchBluetoothDevice.this,
android.R.layout.simple_expandable_list_item_1,deviceList);
deviceListView = (ListView) findViewById(R.id.device_ListView);
deviceListView.setOnItemClickListener(this);
deviceListView.setAdapter(arrayAdapter);
}
private void initBluetooth(){
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();//蓝牙适配器
setBluetoothDevice = bluetoothAdapter.getBondedDevices();//得到本地蓝牙集合
discoveryBroadcast = new DiscoveryBluetoothBroadcast();
DiscoveryFilter = new IntentFilter();
DiscoveryFilter.addAction(BluetoothDevice.ACTION_FOUND);//添加发现设备广播
DiscoveryFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);//开始搜索
DiscoveryFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);//结束搜索广播
this.registerReceiver(discoveryBroadcast,DiscoveryFilter);
if (bluetoothAdapter.isDiscovering()){
bluetoothAdapter.cancelDiscovery();
}
}
public class searchButtonClick implements View.OnClickListener{
@Override
public void onClick(View v) {
Log.d(TAG, "onClick: 开始搜索");
if (bluetoothAdapter.isEnabled()){
if (bluetoothAdapter.isDiscovering()){
Toast.makeText(SearchBluetoothDevice.this,"正在搜索,请不要重复点击",Toast.LENGTH_SHORT).show();
}else {
deviceList.clear();
arrayAdapter.notifyDataSetChanged();
bluetoothAdapter.startDiscovery();//开始搜索
}
}else {
Toast.makeText(SearchBluetoothDevice.this,"请打开蓝牙",Toast.LENGTH_SHORT).show();
Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivity(intent);
}
}
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
message = deviceList.get(position);//得到设备信息
String DialogTitle = "确认连接";
String DialogOk = "连接";
if (message.indexOf("已配对") > -1){//message中查找到"已配对"
DialogTitle = "确认连接";
DialogOk = "连接";
state = false;
}else if (message.indexOf("新设备") > -1){//message中查找到"新设备"
DialogTitle = "确认配对";
DialogOk = "配对";
state = true;
}
message = message.substring(4);//截取第四个字符后面字符串
//创建一个对话框,并设置标题内容
AlertDialog.Builder dialog = new AlertDialog.Builder(SearchBluetoothDevice.this);
dialog.setTitle(DialogTitle);
dialog.setMessage(message);
//dialog.setCancelable(true);//进制返回键
dialog.setPositiveButton(DialogOk, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
BluetoothMsg.BlueToothAddress = message.substring(message.length()-17);//得到硬件地址
bluetoothDevice = bluetoothAdapter.getRemoteDevice(BluetoothMsg.BlueToothAddress);//得到远程设备
if (bluetoothAdapter.isDiscovering()){
bluetoothAdapter.cancelDiscovery();//正在搜索就关闭搜索
Toast.makeText(SearchBluetoothDevice.this,"搜索结束",Toast.LENGTH_SHORT).show();
}
if (state == true){//新设备要配对
try{
Method createBondMethod = BluetoothDevice.class.getMethod("createBond");
createBondMethod.invoke(bluetoothDevice);
}catch (Exception e){
Log.d(TAG, "onClick: 绑定失败");
}
}else if (state == false){//旧设备要连接
if(BluetoothMsg.lastblueToothAddress!=BluetoothMsg.BlueToothAddress){
BluetoothMsg.lastblueToothAddress=BluetoothMsg.BlueToothAddress;
}
Intent intent = new Intent(SearchBluetoothDevice.this,BluetoothChat.class);
startActivity(intent);
}
}
});
dialog.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
BluetoothMsg.BlueToothAddress = null;
}
});
dialog.show();//显示
}
//关于发现的广播
public class DiscoveryBluetoothBroadcast extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction().toString();
int bondState;
switch (action){
case BluetoothDevice.ACTION_FOUND://发现设备
bluetoothDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);//得到该设备
bondState = bluetoothDevice.getBondState();//获得状态
if (bondState == BluetoothDevice.BOND_NONE){
Log.d(TAG, "onReceive: "+bluetoothDevice.getName()+"被发现");
deviceList.add("新设备\n"+"名字:"+bluetoothDevice.getName()+"\n地址:"+bluetoothDevice.getAddress());
arrayAdapter.notifyDataSetChanged();
}else if(bondState == BluetoothDevice.BOND_BONDING){
Log.d(TAG, "onReceive: "+bluetoothDevice.getName()+"正在绑定");
}else if(bondState == BluetoothDevice.BOND_BONDED){
Log.d(TAG, "onReceive: "+bluetoothDevice.getName()+"已绑定");
deviceList.add("已配对\n"+"名字:"+bluetoothDevice.getName()+"\n地址:"+bluetoothDevice.getAddress());
arrayAdapter.notifyDataSetChanged();
}
break;
case BluetoothAdapter.ACTION_DISCOVERY_FINISHED://搜索结束
startBar.setVisibility(View.GONE);
searchButton.setText("开始搜索");
break;
case BluetoothAdapter.ACTION_DISCOVERY_STARTED://搜索开始
startBar.setVisibility(View.VISIBLE);
searchButton.setText("正在搜索...");
break;
}
}
}
@Override
protected void onDestroy() {
super.onDestroy();
this.unregisterReceiver(discoveryBroadcast);
}
}
4.上一篇文章地址
android Bluetooth 开发1之布局和权限点击打开链接
5.继续请看下一篇
android Bluetooth 开发3之数据通信界面点击打开链接
更多推荐
已为社区贡献3条内容
所有评论(0)