80,351
社区成员
发帖
与我相关
我的任务
分享
package com.example.helloworld;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothManager;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
private BluetoothAdapter mBluetoothAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void clickHandler(View source) {
// 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(this, R.string.ble_not_supported, Toast.LENGTH_SHORT).show();
finish();
}
// Initializes a Bluetooth adapter. For API level 18 and above, get a reference to
// BluetoothAdapter through BluetoothManager.
final BluetoothManager bluetoothManager =
(BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
mBluetoothAdapter = bluetoothManager.getAdapter();
// Checks if Bluetooth is supported on the device.
if (mBluetoothAdapter == null) {
// Toast.makeText(this, R.string.error_bluetooth_not_supported, Toast.LENGTH_SHORT).show();
finish();
return;
}
//开启蓝牙
mBluetoothAdapter.enable();
// DeviceScanActivity d = new DeviceScanActivity(mBluetoothAdapter, this);
// d.scanLeDevice(true);
}
}
<uses-feature android:name="android.hardware.bluetooth_le" android:required="true"/>
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
package com.example.helloworld;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattDescriptor;
import android.bluetooth.BluetoothGattService;
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.util.Log;
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.List;
import java.util.UUID;
import android.app.Dialog;
import com.example.helloworld.BluetoothLeClass.OnDataAvailableListener;
import com.example.helloworld.BluetoothLeClass.OnServiceDiscoverListener;
/**
* Activity for scanning and displaying available Bluetooth LE devices.
*/
public class DeviceScanActivity {
private final static String TAG = DeviceScanActivity.class.getSimpleName();
// private final static String UUID_KEY_DATA = "0000ffe1-0000-1000-8000-00805f9b34fb";
private final static String UUID_KEY_RECV_DATA = "0000fff2-0000-1000-8000-00805f9b34fb";
private final static String UUID_KEY_SEND_DATA = "0000fff1-0000-1000-8000-00805f9b34fb";
private LeDeviceListAdapter mLeDeviceListAdapter;
/**搜索BLE终端*/
private BluetoothAdapter mBluetoothAdapter;
/**读写BLE终端*/
private BluetoothLeClass mBLE;
private boolean mScanning;
private Handler mHandler;
// Stops scanning after 10 seconds.
private static final long SCAN_PERIOD = 10000;
// 注册你要用到的变量
public DeviceScanActivity(BluetoothAdapter mBluetoothAdapter, Context c) {
mBLE = new BluetoothLeClass(c);
if (!mBLE.initialize()) {
Log.e(TAG, "Unable to initialize Bluetooth");
// finish();
}
//发现BLE终端的Service时回调
mBLE.setOnServiceDiscoverListener(mOnServiceDiscover);
//收到BLE终端数据交互的事件
mBLE.setOnDataAvailableListener(mOnDataAvailable);
}
// // 点击列表产生的事件
// @Override
// protected void onListItemClick(ListView l, View v, int position, long id) {
// final BluetoothDevice device = mLeDeviceListAdapter.getDevice(position);
// if (device == null) return;
// if (mScanning) {
// mBluetoothAdapter.stopLeScan(mLeScanCallback);
// mScanning = false;
// }
//
// // 连接选择的设备
// mBLE.connect(device.getAddress());
// }
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);
// invalidateOptionsMenu();
// }
// }, SCAN_PERIOD);
mScanning = true;
mBluetoothAdapter.startLeScan(mLeScanCallback);
} else {
mScanning = false;
mBluetoothAdapter.stopLeScan(mLeScanCallback);
}
// invalidateOptionsMenu();
}
/**
* 搜索到BLE终端服务的事件
*/
private BluetoothLeClass.OnServiceDiscoverListener mOnServiceDiscover = new OnServiceDiscoverListener(){
@Override
public void onServiceDiscover(BluetoothGatt gatt) {
displayGattServices(mBLE.getSupportedGattServices());
}
};
/**
* 收到BLE终端数据交互的事件
*/
private BluetoothLeClass.OnDataAvailableListener mOnDataAvailable = new OnDataAvailableListener(){
/**
* BLE终端数据被读的事件
*/
@Override
public void onCharacteristicRead(BluetoothGatt gatt,
BluetoothGattCharacteristic characteristic, int status) {
if (status == BluetoothGatt.GATT_SUCCESS)
Log.e(TAG,"onCharRead "+gatt.getDevice().getName()
+" read "
+characteristic.getUuid().toString()
+" -> "
+Utils.bytesToHexString(characteristic.getValue()));
}
/**
* 收到BLE终端写入数据回调
*/
@Override
public void onCharacteristicWrite(BluetoothGatt gatt,
BluetoothGattCharacteristic characteristic) {
Log.e(TAG,"onCharWrite "+gatt.getDevice().getName()
+" write "
+characteristic.getUuid().toString()
+" -> "
+new String(characteristic.getValue()));
}
};
// 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();
// }
// });
}
};
private void displayGattServices(List<BluetoothGattService> gattServices) {
BluetoothGattCharacteristic notification_gattCharacteristic = null;
BluetoothGattCharacteristic write_gattCharacteristic = null;
if (gattServices == null) return;
for (BluetoothGattService gattService : gattServices) {
List<BluetoothGattCharacteristic> gattCharacteristics = gattService.getCharacteristics();
for (final BluetoothGattCharacteristic gattCharacteristic: gattCharacteristics) {
if(gattCharacteristic.getUuid().toString().equals(UUID_KEY_SEND_DATA)){
notification_gattCharacteristic = gattCharacteristic;
mHandler.postDelayed(new Runnable() {
@Override
public void run() {
mBLE.readCharacteristic(gattCharacteristic);
}
}, 500);
}
if(gattCharacteristic.getUuid().toString().equals(UUID_KEY_RECV_DATA)){
write_gattCharacteristic = gattCharacteristic;
}
}
}
// 找到两个通道,进行处理
mBLE.setCharacteristicNotification(write_gattCharacteristic, true);
//设置数据内容
write_gattCharacteristic.setValue("15200407111810");
//往蓝牙模块写入数据
mBLE.writeCharacteristic(write_gattCharacteristic);
}
}