一、添加蓝牙权限
在AndroidManifest.xml文件中添加如下红色部分代码,添加蓝牙打开权限,以及LE接口调用权限。
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.administrator.myapplication">
<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="true"/>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
二、添加对应的包头以及调用接口,并添加button clock事件开启关闭广播功能。
package com.example.administrator.myapplication;
import android.bluetooth.BluetoothGatt;
import android.support.v7.app.AppCompatActivity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothManager;
import android.bluetooth.le.BluetoothLeAdvertiser;
import android.bluetooth.le.AdvertiseSettings;
import android.bluetooth.le.AdvertiseData;
import android.bluetooth.le.AdvertiseCallback;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button enableBt = (Button)findViewById(R.id.button2);
Button openAdv = (Button)findViewById(R.id.button);
final BluetoothAdapter BtAdapter = BluetoothAdapter.getDefaultAdapter();
final BluetoothLeAdvertiser BtAdv = BtAdapter.getBluetoothLeAdvertiser();
final AdvertiseSettings AdvSetting = new AdvertiseSettings.Builder().build();
final AdvertiseData AdvData = new AdvertiseData.Builder().build();
final AdvertiseCallback AdvCBack = new AdvertiseCallback() {
@Override
public void onStartSuccess(AdvertiseSettings settingsInEffect) {
super.onStartSuccess(settingsInEffect);
Toast.makeText(getApplicationContext(),"start Advertise ok",Toast.LENGTH_SHORT).show();
}
};
enableBt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(BtAdapter.isEnabled() == false){
BtAdapter.enable();
Toast.makeText(getApplicationContext(),"enable bluetooth",Toast.LENGTH_SHORT).show();
}else{
BtAdapter.disable();
Toast.makeText(getApplicationContext(),"disable bluetooth",Toast.LENGTH_SHORT).show();
}
}
});
openAdv.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(BtAdapter.isEnabled()) {
BtAdv.startAdvertising(AdvSetting, AdvData, AdvCBack);
Toast.makeText(getApplicationContext(),"start Advertise",Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(getApplicationContext(),"Bluetooth is not enable!",Toast.LENGTH_SHORT).show();
}
}
});
}
}