资料来源:网峰的APP源码
http://www.smartwebee.com/products_detail/productId=27.html
推荐跟我一起操作,在主页面定义了一个按钮用来刷新,一个用来停止,一个进度条用来提示,一个list用来显示设备列表,这个可以把原来的内容全部删掉,直接复制
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
android:layout_height="match_parent"
android:layout_width="match_parent"
android:orientation="vertical"
xmlns:android="http://schemas.android.com/apk/res/android">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/stop_button"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/scan_button"/>
<ProgressBar
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/progressbar"/>
<ListView
android:id="@+id/id_list_view"
android:layout_width="match_parent"
android:layout_height="match_parent">
</ListView>
</LinearLayout>
第一个代码量比较大的部分就是做列表的适配器,对这部分比较了解的可以快速跳看,核心是围绕着集合mDeviceList在做,浏览时可以Ctrl键+F,查看代码对它的操作
public class MainActivity extends Activity implements View.OnClickListener,AdapterView.OnItemClickListener{
private class ViewHolder{
private TextView deviceName;
private TextView deviceAddress;
}
private class ListViewAdapter extends BaseAdapter{
private ArrayList<BluetoothDevice> mDeviceList;
private LayoutInflater mLayoutInflater;
private ListViewAdapter(){
mDeviceList=new ArrayList<>();
mLayoutInflater=MainActivity.this.getLayoutInflater();
}
private void addDevice(BluetoothDevice device){
if (!mDeviceList.contains(device))mDeviceList.add(device);
}
private void clear(){
mDeviceList.clear();
}
@Override
public int getCount() {
return mDeviceList.size();
}
@Override
public Object getItem(int i) {
return mDeviceList.get(i);
}
@Override
public long getItemId(int i) {
return i;
}
@Override
public View getView(int i, View view, ViewGroup viewGroup) {
ViewHolder viewHolder;
if (view==null){
viewHolder=new ViewHolder();
view=mLayoutInflater.inflate(R.layout.list_view_item, null);
viewHolder.deviceAddress=view.findViewById(R.id.address_text);
viewHolder.deviceName=view.findViewById(R.id.name_text);
view.setTag(viewHolder);
}else {
viewHolder= (ViewHolder) view.getTag();
}
BluetoothDevice device=mDeviceList.get(i);//注意这里
String deviceNameString=device.getName();
if (deviceNameString!=null&&deviceNameString.length()>0){
viewHolder.deviceName.setText(deviceNameString);
}else {
viewHolder.deviceName.setText("其他蓝牙设备");
}
viewHolder.deviceAddress.setText(device.getAddress());
return view;
}
}
}//Activity
相关的listitem
list_view_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">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/name_text"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/address_text"/>
</LinearLayout>
做好了适配器以后,我们进行主体编写
onCreate中都用init函数写,方便调试!
public class MainActivity extends Activity implements View.OnClickListener,AdapterView.OnItemClickListener{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
initData();
initBLE();
initEvent();
}
}
四个函数分别是初始化页面(button),初始化数据(button,handler,adapter),初始化BLE(检查设备是否有蓝牙,请求打开蓝牙),初始化事件(注册按钮点击,设置adapter,扫描函数),可直接复制,记得注册点击事件时在MainActivity 后面implements View.OnClickListener
public class MainActivity extends Activity implements View.OnClickListener,AdapterView.OnItemClickListener{
private Handler handler;
private boolean mScanning;
private Button mScanButton;
private Button mStopButton;
private ProgressBar mProgressBar;
private BluetoothAdapter mBluetoothAdapter;
private ListViewAdapter mListViewAdapter;
private ListView mListView;
private void initView(){
mScanButton=findViewById(R.id.scan_button);
mStopButton=findViewById(R.id.stop_button);
mProgressBar=findViewById(R.id.progressbar);
mListView=findViewById(R.id.id_list_view);
}
private void initData(){
mScanButton.setText("扫描");
mStopButton.setText("停止");
mListViewAdapter=new ListViewAdapter();
handler=new Handler();
}
private void initBLE(){
if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
Toast.makeText(this, "不支持BLE", Toast.LENGTH_SHORT).show();
finish();
}
final BluetoothManager bluetoothManager =
(BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
mBluetoothAdapter = bluetoothManager.getAdapter();
if (mBluetoothAdapter == null) {
Toast.makeText(this, "不支持蓝牙", Toast.LENGTH_SHORT).show();
finish();
}
if (Build.VERSION.SDK_INT >= 23) {
int checkCallPhonePermission = ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION);
if(checkCallPhonePermission != PackageManager.PERMISSION_GRANTED){
if(ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_COARSE_LOCATION))
Toast.makeText(this,"需要定位权限", Toast.LENGTH_LONG).show();
ActivityCompat.requestPermissions(this ,new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},1);
}
}
if (!mBluetoothAdapter.isEnabled()) {
if (!mBluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, 130);
}
}
}
private void initEvent(){
mStopButton.setOnClickListener(this);
mScanButton.setOnClickListener(this);
mListView.setAdapter(mListViewAdapter);
mListView.setOnItemClickListener(this);
Scan(true);
}
}
蓝牙请求结果回调,列表点击事件,按键点击事件
public class MainActivity extends Activity implements View.OnClickListener,AdapterView.OnItemClickListener{
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// User chose not to enable Bluetooth.
if (requestCode == 130 && resultCode == Activity.RESULT_CANCELED) {
finish();
return;
}
super.onActivityResult(requestCode, resultCode, data);
}
@Override
public void onClick(View view) {
switch (view.getId()){
case R.id.scan_button:
mListViewAdapter.clear();
Scan(true);
break;
case R.id.stop_button:
Scan(false);
break;
}
}
private void setButtonVisible(boolean mScanning){
if (!mScanning){
mStopButton.setVisibility(View.GONE);
mScanButton.setVisibility(View.VISIBLE);
mProgressBar.setVisibility(View.GONE);
}else {
mStopButton.setVisibility(View.VISIBLE);
mScanButton.setVisibility(View.GONE);
mProgressBar.setVisibility(View.VISIBLE);
}
}
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
BluetoothDevice device= (BluetoothDevice) mListViewAdapter.getItem(i);
if (device!=null)
Toast.makeText(this,device.getAddress(),Toast.LENGTH_SHORT).show();
}
}
现在来到整篇文章的核心部分,就是扫描方法和回调,两个方法也可以直接复制
BluetoothAdapter.LeScanCallback是蓝牙扫描的回调,核心在于BluetoothDevice的操作,可以按Ctrl键+F看bluetoothDevice的去向
Scan方法用于启动和停止扫描,initEvent中调用了一次,传入true表示进行一次扫描,传入false停止扫描,在按钮的onClick方法中也调用了
public class MainActivity extends Activity implements View.OnClickListener,AdapterView.OnItemClickListener{
private BluetoothAdapter.LeScanCallback mBluetoothAdapterLeScanCallback=new BluetoothAdapter.LeScanCallback() {
@Override
public void onLeScan(final BluetoothDevice bluetoothDevice, int i, byte[] bytes) {
runOnUiThread(new Runnable() {
@Override
public void run() {
mListViewAdapter.addDevice(bluetoothDevice);
mListViewAdapter.notifyDataSetChanged();
}
});
}
};
private void Scan(boolean enable){
if (enable){
handler.postDelayed(new Runnable() {
@Override
public void run() {
mScanning = false;
mBluetoothAdapter.stopLeScan(mBluetoothAdapterLeScanCallback);//会提示需要蓝牙操作权限
setButtonVisible(mScanning);
}
},10000);
mScanning=true;
mBluetoothAdapter.startLeScan(mBluetoothAdapterLeScanCallback);
}else {
mScanning=false;
mBluetoothAdapter.stopLeScan(mBluetoothAdapterLeScanCallback);
}
setButtonVisible(mScanning);
}
}
清单文件,这里几个权限要注意,一般这里出错比较多
除了蓝牙权限外,如果需要BLE feature则还需要声明uses-feature
required为true时,则应用只能在支持BLE的Android设备上安装运行;required为false时,Android设备均可正常安装运行,需要在代码运行时判断设备是否支持BLE feature,就是前面initBLE()中的FEATURE_BLUETOOTH_LE判断
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.a123">
<uses-feature android:name="android.hardware.bluetooth_le" android:required="true"/>
<uses-feature android:name="android.bluetooth.le" android:required="true"/>
<uses-permission android:name="android.permission.BLUETOOTH_PRIVILEGED" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>