手机BLE蓝牙通讯

Android的蓝牙开发,包括蓝牙的广播事件和扫描,蓝牙配对连接、数据传输等问题,本文着重讲BLE低功耗蓝牙4.0开发

AndroidMainifest权限:

    <uses-sdk
        android:minSdkVersion="18"
        android:targetSdkVersion="19" />

    <!--蓝牙权限-->
    <uses-permission android:name="android.permission.BLUETOOTH"/>
    <uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
    <!--Android 5.0以上蓝牙好需要位置权限-->
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
    <uses-permission android:name="andriod.permission.ACCESS_FINE_LOCATION"/>
    <!--设备支持BLE低功耗蓝牙 true -->
    <uses-feature android:name="android.hardware.bluetooth_le" android:required="true"></uses-feature>

△低功耗蓝牙4.0开发:源码

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import android.app.Activity;
import android.app.AlertDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattDescriptor;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.BluetoothProfile;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.pm.PackageManager;
public class MainActivity extends Activity {
	private BluetoothAdapter mBluetoothAdapter;
	private Handler mHandler=new Handler();
	private boolean mScanning;
	private BluetoothGatt mGatt;
	private BluetoothGattCharacteristic mGattCharacteristic;
	
	private ListView mlv;//自定义列表listview
	private BleAdapter mBleAdapter;//自定义适配器adapter
	private ArrayList<BluetoothDevice> mArray=new ArrayList<BluetoothDevice>();//自定义容器
	private EditText mEdit;//自定义edittext
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		initUI();
		initBLE();
	}
	
	@Override
	protected void onDestroy() {
		if(mGatt!=null){
			mGatt.close();
			mGatt=null;
		}
		super.onDestroy();
	}
	
	//初始化自定义控件
	private void initUI(){
		findViewById(R.id.button1).setOnClickListener(new View.OnClickListener() {
	
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值