基本信息
源码名称:Bluetooth_4.3 BLE蓝牙通信
源码大小:1.55M
文件格式:.rar
开发语言:Java
更新时间:2015-09-15
友情提示:(无需注册或充值,赞助后即可获取资源下载链接)
嘿,亲!知识可是无价之宝呢,但咱这精心整理的资料也耗费了不少心血呀。小小地破费一下,绝对物超所值哦!如有下载和支付问题,请联系我们QQ(微信同号):813200300
本次赞助数额为: 2 元×
微信扫码支付:2 元
×
请留下您的邮箱,我们将在2小时内将文件发到您的邮箱
源码介绍
用处不大
/* * Copyright (C) 2013 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.bluetooth.le; import android.annotation.SuppressLint; import android.app.ActionBar; import android.app.Activity; import android.app.ListActivity; import android.bluetooth.BluetoothAdapter; 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.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import java.util.ArrayList; import java.util.UUID; /** * Activity for scanning and displaying available Bluetooth LE devices. */ @SuppressLint("NewApi") public class DeviceScanActivity extends ListActivity { private LeDeviceListAdapter mLeDeviceListAdapter; private BluetoothAdapter mBluetoothAdapter; private boolean mScanning; private Handler mHandler; private ActionBar mActionBar = null; private static final int REQUEST_ENABLE_BT = 1; // 10秒后停止查找搜索. private static final long SCAN_PERIOD = 10000; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mActionBar = getActionBar(); mActionBar.setTitle("Ken Ble Scan"); //mActionBar.setTitle(R.string.title_devices); mHandler = new Handler(); // 检查当前手机是否支持ble 蓝牙,如果不支持退出程序 if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) { Toast.makeText(this, R.string.ble_not_supported, Toast.LENGTH_SHORT).show(); finish(); } // 初始化 Bluetooth adapter, 通过蓝牙管理器得到一个参考蓝牙适配器(API必须在以上android4.3或以上和版本) final BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE); mBluetoothAdapter = bluetoothManager.getAdapter(); // 检查设备上是否支持蓝牙 if (mBluetoothAdapter == null) { Toast.makeText(this, R.string.error_bluetooth_not_supported, Toast.LENGTH_SHORT).show(); finish(); return; } } //======================end of oncreate @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main, menu); if (!mScanning) { System.out.println(" Didnot Scan ==="); menu.findItem(R.id.menu_stop).setVisible(false); menu.findItem(R.id.menu_scan).setVisible(true); menu.findItem(R.id.menu_refresh).setActionView(null); } else { System.out.println(" Scaning ==== "); menu.findItem(R.id.menu_stop).setVisible(true); menu.findItem(R.id.menu_scan).setVisible(false); menu.findItem(R.id.menu_refresh).setActionView( R.layout.actionbar_indeterminate_progress); } return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.menu_scan: mLeDeviceListAdapter.clear(); scanLeDevice(true); break; case R.id.menu_stop: scanLeDevice(false); break; } return true; } @Override protected void onResume() { super.onResume(); //其实这个是 每次回到这个界面 或刚启动的时候都会执行到的一句话 System.out.println("ON Resume "); // 为了确保设备上蓝牙能使用, 如果当前蓝牙设备没启用,弹出对话框向用户要求授予权限来启用 if (!mBluetoothAdapter.isEnabled()) { if (!mBluetoothAdapter.isEnabled()) { Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT); } } // Initializes list view adapter. 蓝牙列表适配器 很专业的样子 继承的是 listactivity 所以可以直接设置 适配器 之后开启蓝牙搜索 mLeDeviceListAdapter = new LeDeviceListAdapter(); setListAdapter(mLeDeviceListAdapter); scanLeDevice(true); }//end of onresume @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { // User chose not to enable Bluetooth. if (requestCode == REQUEST_ENABLE_BT && resultCode == Activity.RESULT_CANCELED) { finish(); return; } super.onActivityResult(requestCode, resultCode, data); }//end of onactivityresult @Override protected void onPause() { super.onPause(); scanLeDevice(false); mLeDeviceListAdapter.clear(); } //到这里 还没有连接设备 只是 开启了另一个activity 并将地址还有设备名传过去了。 @Override protected void onListItemClick(ListView l, View v, int position, long id) { //扫描到的是一个蓝牙列表 通过位置得到 要连接的是哪一个。 final BluetoothDevice device = mLeDeviceListAdapter.getDevice(position); if (device == null) return; final Intent intent = new Intent(this, DeviceControlActivity.class); intent.putExtra(DeviceControlActivity.EXTRAS_DEVICE_NAME, device.getName()); intent.putExtra(DeviceControlActivity.EXTRAS_DEVICE_ADDRESS, device.getAddress()); if (mScanning) { mBluetoothAdapter.stopLeScan(mLeScanCallback); mScanning = false; } startActivity(intent); } //这个函数可以启动 蓝牙搜索 十秒之后结束 private 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); invalidateOptionsMenu(); } }, SCAN_PERIOD); mScanning = true; mBluetoothAdapter.startLeScan(mLeScanCallback); } else { mScanning = false; mBluetoothAdapter.stopLeScan(mLeScanCallback); } invalidateOptionsMenu(); } // Adapter for holding devices found through scanning. //蓝牙列表 这个列表是从baseadapter继承来的,继承这个类需要实现4个 方法, private class LeDeviceListAdapter extends BaseAdapter { private ArrayList<BluetoothDevice> mLeDevices; private LayoutInflater mInflator; //构造方法 创建这个类的时候就 创建一个蓝牙列表 还有创建 一个XML====================== public LeDeviceListAdapter() { super(); mLeDevices = new ArrayList<BluetoothDevice>(); mInflator = DeviceScanActivity.this.getLayoutInflater(); } //================蓝牙设备列表 添加 蓝牙 这个方法被scancallback调用 添加设备 public void addDevice(BluetoothDevice device) { if(!mLeDevices.contains(device)) { mLeDevices.add(device); } } //得到蓝牙设备 传入的是listadepter的position 返回的是设备列表中的第 position个设备 public BluetoothDevice getDevice(int position) { return mLeDevices.get(position); } //clear 蓝牙列表=================== public void clear() { mLeDevices.clear(); } //得到蓝牙列表的数量 @Override public int getCount() { return mLeDevices.size(); } //返回第I个device @Override public Object getItem(int i) { return mLeDevices.get(i); } //这个函数是得到点击的 是第几个item @Override public long getItemId(int i) { return i; } //这个getview 里面的内容就是将设备的名字以及地址写入了text中 @Override public View getView(int i, View view, ViewGroup viewGroup) { ViewHolder viewHolder; // General ListView optimization code. if (view == null) { view = mInflator.inflate(R.layout.listitem_device, 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(); } //这里就是关键的地方了,可以得到蓝牙list中的某个设备 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; } }//end of ledevicelistadapter // Device scan callback. 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(); } }); } };//===============end of lescancallback 这个callback 函数 会将device 传过来 这里可以添加设备 static class ViewHolder { TextView deviceName; TextView deviceAddress; } }