蓝牙 开发 入门 小实例 (寻找连接阶段)


 <uses-permission android:name="android.permission.BLUETOOTH"/>
    <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />


activity_main.xml


<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context="com.moliying.bluetooth.MainActivity">

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="openClick"
        android:text="查找蓝牙"
        android:id="@+id/openBlueTooth"/>

    <ListView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/listView_blueTooth"
        android:layout_below="@+id/openBlueTooth"
        android:layout_alignParentStart="true" />
</RelativeLayout>



bluetooth_item.xml


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="@dimen/activity_horizontal_margin">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="name"
        android:id="@+id/textView_name" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="address"
        android:id="@+id/textView2_address" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="配对状态"
        android:id="@+id/textView_bond" />
</LinearLayout>


MainActivity


package com.moliying.bluetooth;

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.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity implements AdapterView.OnItemClickListener {

    private static final int REQUEST_ENABLE = 0x1;
    private ListView listView_bluetooth;
    private MyAdapter myAdapter;
    private List<BluetoothDevice> deviceList = new ArrayList<>();
    BluetoothAdapter bluetoothAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        listView_bluetooth = (ListView) findViewById(R.id.listView_blueTooth);
        myAdapter = new MyAdapter(this,deviceList);
        listView_bluetooth.setAdapter(myAdapter);
        listView_bluetooth.setOnItemClickListener(this);
    }
    public void openClick(View v){
        deviceList.clear();
        //提示用户是否打开蓝牙
//        Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
//        startActivityForResult(intent,REQUEST_ENABLE);

        //直接打开蓝牙
        bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        bluetoothAdapter.enable();

        if(bluetoothAdapter.isEnabled()){
            bluetoothAdapter.startDiscovery(); //开始扫描设备
        }
    }

    private BlueToothReceiver receiver = new BlueToothReceiver();
    @Override
    protected void onStart() {
        super.onStart();
        //注册广播接收器
        IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        registerReceiver(receiver,filter);
    }

    @Override
    protected void onStop() {
        //取消注册
        unregisterReceiver(receiver);
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        bluetoothAdapter.cancelDiscovery();
        myAdapter = null;
        deviceList = null;
        super.onDestroy();
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        bluetoothAdapter.cancelDiscovery();//取消查找
        BluetoothDevice device = deviceList.get(position);
        int state = device.getBondState();
        switch (state){
            case BluetoothDevice.BOND_NONE:
                //发现了没有配对的设备
//                    device.createBond(); //该方法在API19后可以使用
                try {
                    //API19以下版本可便用反射来调用配对的方法
                    Method createBondMethod = BluetoothDevice.class.getMethod("createBond");
                    createBondMethod.invoke(device);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
        }
    }

    private static class MyAdapter extends BaseAdapter{
        private Context context;
        private List<BluetoothDevice> list;
        public MyAdapter(Context context, List<BluetoothDevice> list) {
            this.context = context;
            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 position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder vh = null;
            if(convertView==null){
                convertView = LayoutInflater.from(context).inflate(R.layout.bluetooth_item,null);
                vh = new ViewHolder();
                vh.textView_name = (TextView) convertView.findViewById(R.id.textView_name);
                vh.textView_address = (TextView) convertView.findViewById(R.id.textView2_address);
                vh.textView_bond = (TextView) convertView.findViewById(R.id.textView_bond);
                convertView.setTag(vh);
            }else{
                vh = (ViewHolder) convertView.getTag();
            }
            BluetoothDevice bd = list.get(position);
            vh.textView_name.setText(bd.getName());
            vh.textView_address.setText(bd.getAddress());
            String bond = "";
            switch (bd.getBondState()){
                case BluetoothDevice.BOND_NONE:
                    bond = "未配对";
                    break;
                case BluetoothDevice.BOND_BONDED:
                    bond = "已配对";
                    break;
                default:
                    bond = "未知";
            }
            vh.textView_bond.setText(bond);

            return convertView;
        }
        static class ViewHolder{
            TextView textView_name;
            TextView textView_address;
            TextView textView_bond;
        }
    }

    //发现蓝牙设备后用于接收设备
    class BlueToothReceiver extends BroadcastReceiver{
        @Override
        public void onReceive(Context context, Intent intent) {
            BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            Log.i("BlueToothReceiver", "onReceive: "+device.getName()+"-"+device.getAddress());
            deviceList.add(device);
            myAdapter.notifyDataSetChanged();
        }
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值