话不多说直接上代码:
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<PhoneDate> list = new ArrayList<PhoneDate>(); private PhoneDate phoneDate = new PhoneDate(); List<String> lstDevices = new ArrayList<String>(); @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<String> list; public BuleToothAdapter(Context mContext, List<String> 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.权限:
<uses-permission android:name="android.permission.BLUETOOTH" /> <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
4.布局:acvivity_main
<?xml version="1.0" encoding="utf-8"?> <LinearLayout 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" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".MainActivity"> <RelativeLayout android:layout_width="match_parent" android:layout_height="50dp" android:background="#968366"> <TextView android:id="@+id/textswitch" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" android:layout_centerVertical="true" android:layout_marginLeft="59dp" android:layout_marginStart="59dp" android:text="关闭" android:textSize="20sp" /> <Switch android:id="@+id/switchview" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentEnd="true" android:layout_alignParentRight="true" android:layout_centerVertical="true" android:layout_marginEnd="38dp" android:layout_marginRight="38dp" /> </RelativeLayout> <TextView android:id="@+id/textprompt" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center" android:maxLines="2" android:paddingLeft="20dp" android:paddingRight="20dp" android:text="开启蓝牙后,您的设备可以与附近的其他蓝牙设备通信。" android:textSize="20sp" android:visibility="gone" /> <TextView android:id="@+id/texttilte" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="1dp" android:background="#ff848484" android:paddingBottom="5dp" android:paddingLeft="10dp" android:paddingTop="5dp" android:text="可用设备" android:textColor="#ff66ff00" android:textSize="16sp" /> <RelativeLayout android:layout_width="match_parent" android:layout_height="match_parent"> <ListView android:id="@+id/listview_prompt" android:layout_width="match_parent" android:layout_height="wrap_content"></ListView> <Button android:id="@+id/button" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" android:onClick="onClick" android:text="搜索设备" /> </RelativeLayout> </LinearLayout>layout_adapter:
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:id="@+id/textView" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignParentEnd="true" android:layout_alignParentRight="true" android:drawableLeft="@mipmap/bluetooth" android:drawableRight="@mipmap/arrowright" android:ellipsize="middle" android:gravity="left|center" android:maxLines="1" android:paddingBottom="5dp" android:paddingLeft="15dp" android:paddingRight="15dp" android:paddingTop="5dp" android:text="手机型号:" android:textSize="18sp" /> <TextView android:id="@+id/isconnect" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignBottom="@+id/textView" android:layout_alignParentEnd="true" android:layout_alignParentRight="true" android:layout_marginBottom="2dp" android:layout_marginEnd="61dp" android:layout_marginRight="61dp" /> </RelativeLayout>
5.实际效果图: