Android 学习笔记7——蓝牙4.0LE:搜索设备

嗯,这一周我研究了一下蓝牙4.0LE的相关内容,目前是可以搜索到设备了。原本是想等到搜索、配对、传数据都成功之后再写的,突然超哥说先把蓝牙放一放,先打通Wi-Fi,所以就先写一下BLE情况下的搜索设备。所用的是一块Smart RF板子与移动的M812手机,主要代码参考的是官方文档。

Java文件:

package com.example.ble;

import java.util.ArrayList;

import android.app.Activity;
import android.app.ListActivity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothAdapter.LeScanCallback;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListAdapter;
import android.widget.TextView;
import android.widget.Toast;



public class MainActivity extends ListActivity {
    BluetoothAdapter mBluetoothAdapter;
    static int REQUEST_ENABLE_BT = 1;
    private boolean mScanning;
    private Handler mHandler;
    //private Handler mHandler = new Handler();
    private String kk;
    private LeDeviceListAdapter mLeDeviceListAdapter;
    private BluetoothAdapter.LeScanCallback mLeScanCallback =
	        new BluetoothAdapter.LeScanCallback() {
	    @Override
	    public void onLeScan(final BluetoothDevice device, int rssi,
	            byte[] scanRecord) {
	    	runOnUiThread(new Runnable() {
	            @Override
	            public void run() {
	                mLeDeviceListAdapter.addDevice(device);
	                mLeDeviceListAdapter.notifyDataSetChanged();
	            }
	        });
	   }
	};
    
    // Stops scanning after 10 seconds.
    private static final long SCAN_PERIOD = 10000;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mHandler = new Handler();
        final BluetoothManager bluetoothManager = (BluetoothManager)getSystemService(Context.BLUETOOTH_SERVICE);
		mBluetoothAdapter = bluetoothManager.getAdapter();
        //setListAdapter(mLeDeviceListAdapter);
        //setContentView(R.layout.activity_main);
		// Use this check to determine whether BLE is supported on the device. Then
		// you can selectively disable BLE-related features.
		if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
		    Toast.makeText(getApplicationContext(), R.string.ble_not_supported, Toast.LENGTH_SHORT).show();
		    finish();
		}
	
		// Ensures Bluetooth is available on the device and it is enabled. If not,
		// displays a dialog requesting user permission to enable Bluetooth.
		if (mBluetoothAdapter == null || !mBluetoothAdapter.isEnabled()) {
		    Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
		    startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
		}
		
		//scanLeDevice(true);
        mLeDeviceListAdapter = new LeDeviceListAdapter();
        setListAdapter(mLeDeviceListAdapter);
        scanLeDevice(true);
	}
	
    public void scanLeDevice (final boolean enable){
	    if (enable) {
	        // Stops scanning after a pre-defined scan period.
	    	mHandler.postDelayed(new Runnable() {
	            @Override
	            public void run() {
	                mScanning = false;
					mBluetoothAdapter.stopLeScan(mLeScanCallback);
	            }
	        }, SCAN_PERIOD);
	
	        mScanning = true;
	        mBluetoothAdapter.startLeScan(mLeScanCallback);
	    } else {
	        mScanning = false;
	        mBluetoothAdapter.stopLeScan(mLeScanCallback);
	    }
    }
	
	// Adapter for holding devices found through scanning.
    private class LeDeviceListAdapter extends BaseAdapter {
        private ArrayList<BluetoothDevice> mLeDevices;
        private LayoutInflater mInflator;
 
        public LeDeviceListAdapter() {
            super();
            mLeDevices = new ArrayList<BluetoothDevice>();
            mInflator = MainActivity.this.getLayoutInflater();
        }
 
        public void addDevice(BluetoothDevice device) {
            if(!mLeDevices.contains(device)) {
                mLeDevices.add(device);
            }
        }
 
        public BluetoothDevice getDevice(int position) {
            return mLeDevices.get(position);
        }
 
        public void clear() {
            mLeDevices.clear();
        }
 
        @Override
        public int getCount() {
            return mLeDevices.size();
        }
 
        @Override
        public Object getItem(int i) {
            return mLeDevices.get(i);
        }
 
        @Override
        public long getItemId(int i) {
            return i;
        }
 
        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {
            ViewHolder viewHolder;
            // General ListView optimization code.
            if (view == null) {
                view = mInflator.inflate(R.layout.activity_main, null);
                viewHolder = new ViewHolder();
                viewHolder.deviceAddress = (TextView) view.findViewById(R.id.device_address);
                viewHolder.deviceName = (TextView) view.findViewById(R.id.device_name);
                view.setTag(viewHolder);
            } else {
                viewHolder = (ViewHolder) view.getTag();
            }
 
            BluetoothDevice device = mLeDevices.get(i);
            final String deviceName = device.getName();
            if (deviceName != null && deviceName.length() > 0)
                viewHolder.deviceName.setText(deviceName);
            else
                viewHolder.deviceName.setText(R.string.unknown_device);
            viewHolder.deviceAddress.setText(device.getAddress());
 
            return view;
        }
    }
    static class ViewHolder {
        TextView deviceName;
        TextView deviceAddress;
    }
	
}
xml文件:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="match_parent"
              android:layout_height="wrap_content">
    <TextView android:id="@+id/device_name"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textSize="24dp"/>
    <TextView android:id="@+id/device_address"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textSize="12dp"/>
</LinearLayout>

Manifest文件中注意添加:
	<uses-permission android:name="android.permission.BLUETOOTH"/>
	<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
	<uses-feature android:name="android.hardware.bluetooth_le" android:required="false"/>


你可能感兴趣的:(android,搜索,蓝牙)