博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Android 设置中的蓝牙
阅读量:3760 次
发布时间:2019-05-22

本文共 10087 字,大约阅读时间需要 33 分钟。

话不多说直接上代码:

1.Activity:

package com.vstar3d.buletoothdemo;import android.bluetooth.BluetoothAdapter;import android.bluetooth.BluetoothDevice;import android.bluetooth.BluetoothSocket;import android.content.BroadcastReceiver;import android.content.Context;import android.content.Intent;import android.content.IntentFilter;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.Button;import android.widget.CompoundButton;import android.widget.ListView;import android.widget.Switch;import android.widget.TextView;import android.widget.Toast;import java.io.IOException;import java.lang.reflect.Method;import java.util.ArrayList;import java.util.List;import java.util.UUID;public class MainActivity extends AppCompatActivity implements CompoundButton.OnCheckedChangeListener, AdapterView.OnItemClickListener {    private TextView textswitch, textprompt, texttilte;    private Switch switchview;    private BluetoothAdapter mBluetoothAdapter;    private Button button;    private ListView lvNewDevices;    private BuleToothAdapter adapter;    private List
list = new ArrayList
(); private PhoneDate phoneDate = new PhoneDate(); List
lstDevices = new ArrayList
(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textswitch = (TextView) findViewById(R.id.textswitch); textprompt = (TextView) findViewById(R.id.textprompt); textprompt.setVisibility(View.VISIBLE); texttilte = (TextView) findViewById(R.id.texttilte); switchview = (Switch) findViewById(R.id.switchview); lvNewDevices = (ListView) findViewById(R.id.listview_prompt); button = (Button) findViewById(R.id.button); adapter = new BuleToothAdapter(this, lstDevices); mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); if (mBluetoothAdapter == null) { Toast.makeText(this, "设备不支持蓝牙", Toast.LENGTH_SHORT).show(); return; } IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction(BluetoothDevice.ACTION_FOUND); intentFilter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED); intentFilter.addAction(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED); intentFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED); registerReceiver(mReceiver, intentFilter); switchview.setOnCheckedChangeListener(this); lvNewDevices.setOnItemClickListener(this); lvNewDevices.setAdapter(adapter); adapter.notifyDataSetChanged(); } public void onClick(View view) { button.setEnabled(false); button.setText("搜索中..."); setTitle("搜索中..."); if (mBluetoothAdapter.getState() == BluetoothAdapter.STATE_OFF) { Toast.makeText(MainActivity.this, "请先打开蓝牙", Toast.LENGTH_SHORT).show(); return; } if (mBluetoothAdapter.isDiscovering()) mBluetoothAdapter.cancelDiscovery(); list.clear(); Object[] lstDevice = mBluetoothAdapter.getBondedDevices().toArray(); for (int i = 0; i < lstDevice.length; i++) { BluetoothDevice device = (BluetoothDevice) lstDevice[i]; String str = "已配对|" + device.getName() + "|" + device.getAddress(); phoneDate.setConnectState(device.getBondState()); phoneDate.setName(str); lstDevices.add(str); adapter.notifyDataSetChanged(); } mBluetoothAdapter.startDiscovery(); } @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked) { textprompt.setVisibility(View.GONE); textswitch.setText("开启"); mBluetoothAdapter.enable();//打开蓝牙 Intent discoverableIntent = new Intent( BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE); discoverableIntent.putExtra( BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 0); startActivity(discoverableIntent); mBluetoothAdapter.getAddress(); mBluetoothAdapter.getName(); } else { textprompt.setVisibility(View.VISIBLE); textswitch.setText("关闭"); mBluetoothAdapter.disable();//关闭蓝牙 } } private final BroadcastReceiver mReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); Bundle b = intent.getExtras(); Object[] lstName = b.keySet().toArray(); // 显示所有收到的消息及其细节 for (int i = 0; i < lstName.length; i++) { String keyName = lstName[i].toString(); Log.e(keyName, String.valueOf(b.get(keyName))); } BluetoothDevice device = null; // 搜索设备时,取得设备的MAC地址 if (BluetoothDevice.ACTION_FOUND.equals(action)) { device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); if (device.getBondState() == BluetoothDevice.BOND_NONE) { String str = "未配对|" + device.getName() + "|" + device.getAddress(); if (list.indexOf(str) == -1)// 防止重复添加 phoneDate.setConnectState(device.getBondState()); phoneDate.setName(str); // list.add(phoneDate); // 获取设备名称和mac地址 lstDevices.add(str); adapter.notifyDataSetChanged(); } } else if (BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)) { device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); switch (device.getBondState()) { case BluetoothDevice.BOND_BONDING: Log.d("BlueToothTestActivity", "正在配对......"); break; case BluetoothDevice.BOND_BONDED: Log.d("BlueToothTestActivity", "完成配对"); try { connect(device);//连接设备 } catch (IOException e) { e.printStackTrace(); } break; case BluetoothDevice.BOND_NONE: Log.d("BlueToothTestActivity", "取消配对"); default: break; } } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) { button.setEnabled(true); setTitle("蓝牙"); button.setText("搜索设备"); } } }; private void connect(BluetoothDevice device) throws IOException { // 固定的UUID final String SPP_UUID = "00001101-0000-1000-8000-00805F9B34FB"; UUID uuid = UUID.fromString(SPP_UUID); BluetoothSocket socket = device.createRfcommSocketToServiceRecord(uuid); socket.connect(); } @Override protected void onDestroy() { super.onDestroy(); if (mBluetoothAdapter != null) { mBluetoothAdapter.cancelDiscovery(); } unregisterReceiver(mReceiver); } @Override public void onItemClick(AdapterView
parent, View view, int position, long id) { if (mBluetoothAdapter.isDiscovering()) mBluetoothAdapter.cancelDiscovery(); String str = lstDevices.get(position); String[] values = str.split("\\|"); String address = values[2]; Log.e("address", values[2]); BluetoothDevice btDev = mBluetoothAdapter.getRemoteDevice(address); try { Boolean returnValue = false; if (btDev.getBondState() == BluetoothDevice.BOND_NONE) { Method createBondMethod = BluetoothDevice.class .getMethod("createBond"); Log.d("BlueToothTestActivity", "开始配对"); returnValue = (Boolean) createBondMethod.invoke(btDev); } else if (btDev.getBondState() == BluetoothDevice.BOND_BONDED) { connect(btDev); } } catch (Exception e) { e.printStackTrace(); } }}

2.adapter:

package com.vstar3d.buletoothdemo;import android.content.Context;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.BaseAdapter;import android.widget.TextView;import java.util.List;public class BuleToothAdapter extends BaseAdapter {    private Context mContext;    private List
list; public BuleToothAdapter(Context mContext, List
list) { this.mContext = mContext; this.list = list; } @Override public int getCount() { return list.size(); } @Override public Object getItem(int position) { return list.get(position); } @Override public long getItemId(int position) { return 0; } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder viewHolder; if (convertView == null){ convertView = LayoutInflater.from(mContext).inflate(R.layout.layout_buletooth_adapter,null); viewHolder = new ViewHolder(); viewHolder.textView = (TextView) convertView.findViewById(R.id.textView); viewHolder.isconnect = (TextView) convertView.findViewById(R.id.isconnect); convertView.setTag(viewHolder); }else { viewHolder = (ViewHolder) convertView.getTag(); } String stringTitle = list.get(position); viewHolder.textView.setText(stringTitle); return convertView; } class ViewHolder{ TextView textView; TextView isconnect; }}

3.权限:

4.布局:acvivity_main

layout_adapter:

5.实际效果图:

你可能感兴趣的文章
Spring Boot整合MyBatis
查看>>
Spring Boot整合JPA
查看>>
Spring Boot整合Redis
查看>>
Thymeleaf模板引擎
查看>>
使用Thymeleaf配置国际化页面
查看>>
Spring Boot中Spring MVC的整合支持
查看>>
Spring Boot制作个人博客-首页
查看>>
Spring Boot制作个人博客-详情页
查看>>
Spring Boot制作个人博客-分类页
查看>>
Spring Boot制作个人博客-标签页
查看>>
Spring Boot制作个人博客-归档页
查看>>
Spring Boot制作个人博客-关于我页
查看>>
Spring Boot制作个人博客-博客管理列表页
查看>>
周总结11
查看>>
Spring Boot制作个人博客-博客关于我页面
查看>>
2021-06-12# 学习以及成为想要成为的人day17
查看>>
# 学习以及成为想要成为的人day18
查看>>
学习以及成为想要成为的人day19
查看>>
#学习以及成为想要成为的人day20
查看>>
servlet500
查看>>