android 蓝牙4.0广播功能应用
16lz
2021-01-23
一、添加蓝牙权限
在AndroidManifest.xml文件中添加如下红色部分代码,添加蓝牙打开权限,以及LE接口调用权限。
<?xml version="1.0" encoding="utf-8"?>
二、添加对应的包头以及调用接口,并添加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(); } } }); }}
更多相关文章
- android M上可能需要开发者注意的权限大全
- Android蓝牙操作
- Android bluetooth介绍(二): android 蓝牙代码架构及其uart 到rfcom
- android apk获得系统权限
- Android Bluetooth 学习(2)应用层实现蓝牙设备查找、tcp_ip通信
- Android应用程序永久获取root权限方法
- Android基于ProductFlavors动态配置权限
- android ble蓝牙开发略解-Android 蓝牙4.0开发
- Android 中文API (70) ―― BluetoothDevice[蓝牙]