1. 程式人生 > >利用藍芽廣播資料

利用藍芽廣播資料

一個Activity搞定.

在自定義一個myAppliction繼承系統的Appliction,我在onCreate()裡進行自動開啟藍芽.

 

public class MyApplication extends Application {
@Override
public void onCreate() {
    super.onCreate();
    BluetoothAdapter blueadapter = BluetoothAdapter.getDefaultAdapter();
    if(blueadapter!=null) {  //Device support Bluetooth
        //確認開啟藍芽
        if (!blueadapter.isEnabled()) {
            //直接開啟,不經過提示
            blueadapter.enable();
        }
    }

 

MainActivity 裡面的程式碼.

 

public class MainActivityextends AppCompatActivity{
private BluetoothAdapter mBluetoothAdapter;
private static final String TAG = "bleperipheral";
private static final String HEART_RATE_SERVICE = "0000180d-0000-1000-8000-00805f9b34fb"; 
private BluetoothLeAdvertiser mBluetoothLeAdvertiser;
//回撥
private AdvertiseCallback mAdvertiseCallback = new AdvertiseCallback() {
    @Override
    //成功
    public void onStartSuccess(AdvertiseSettings settingsInEffect) {
        super.onStartSuccess(settingsInEffect);
        if (settingsInEffect != null) {
            Log.d(TAG, "onStartSuccess TxPowerLv=" + settingsInEffect.getTxPowerLevel() + " mode=" + settingsInEffect.getMode()
                    + " timeout=" + settingsInEffect.getTimeout());
        } else {
            Log.e(TAG, "onStartSuccess, settingInEffect is null");
        }
        Log.e(TAG, "onStartSuccess settingsInEffect" + settingsInEffect);
    }
    //失敗
    @Override
    public void onStartFailure(int errorCode) {
        super.onStartFailure(errorCode);
        Log.e(TAG, "onStartFailure errorCode" + errorCode);//返回的錯誤碼
        if (errorCode == ADVERTISE_FAILED_DATA_TOO_LARGE) {
            Toast.makeText(Utils.getContext(), "廣播開啟錯誤,資料大於31個位元組", Toast.LENGTH_LONG).show();
            Log.e(TAG, "廣播開啟錯誤,資料大於31個位元組");
        } else if (errorCode == ADVERTISE_FAILED_TOO_MANY_ADVERTISERS) {

            Toast.makeText(Utils.getContext(), "未能開始廣播,沒有廣播例項", Toast.LENGTH_LONG).show();
            Log.e(TAG, "未能開始廣播,沒有廣播例項");

        } else if (errorCode == ADVERTISE_FAILED_ALREADY_STARTED) {

            Toast.makeText(Utils.getContext(), "正在連線的,無法再次連線", Toast.LENGTH_LONG).show();
            Log.e(TAG, "正在連線的,無法再次連線");

        } else if (errorCode == ADVERTISE_FAILED_INTERNAL_ERROR) {

            Toast.makeText(Utils.getContext(), "由於內部錯誤操作失敗", Toast.LENGTH_LONG).show();
            Log.e(TAG, "由於內部錯誤操作失敗");

        } else if (errorCode == ADVERTISE_FAILED_FEATURE_UNSUPPORTED) {

            Toast.makeText(Utils.getContext(), "在這個平臺上不支援此功能", Toast.LENGTH_LONG).show();
            Log.e(TAG, "在這個平臺上不支援此功能");
        }
    }
};@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    init();
 }
 //初始化資料
    private void init() {
        if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
            Toast.makeText(this, "不支援", Toast.LENGTH_LONG).show();
            finish();
        }
        final BluetoothManager mBluetoothManager = (BluetoothManager) getSystemService(BLUETOOTH_SERVICE);
        mBluetoothAdapter = mBluetoothManager.getAdapter();

        if (mBluetoothAdapter == null) {
            Toast.makeText(this, "未配對藍芽", Toast.LENGTH_LONG).show();
            finish();
        }
        mBluetoothLeAdvertiser = mBluetoothAdapter.getBluetoothLeAdvertiser();//判斷你的裝置到底支援不支援BLE Peripheral。假如此返回值非空,你才可以繼續有機會開發
        if (mBluetoothLeAdvertiser == null) {
            Toast.makeText(this, "不支援BLE Peripheral", Toast.LENGTH_SHORT).show();
            Log.e(TAG, "不支援BLE Peripheral");
            finish();
        }

        //開啟藍芽廣播  一個是廣播設定引數,一個是廣播資料,還有一個是Callback
        mBluetoothLeAdvertiser.startAdvertising(createAdvSettings(true, 0), createAdvertiseData(), mAdvertiseCallback);
        Toast.makeText(Utils.getContext(), "開啟廣播", Toast.LENGTH_LONG).show();
        Log.e(TAG, "開啟廣播");
    }

    /**
     * 初始化藍芽類
     * AdvertisingSettings.Builder 用於建立AdvertiseSettings
     * AdvertiseSettings中包含三種資料:AdvertiseMode, Advertise TxPowerLevel和AdvertiseType,其測試結果如下:
     * AdvertiseMode:
     * Advertise Mode                           Logcat頻率                   檢測到的頻率
     * ADVERTISE_MODE_LOW_LATENCY          1/1600 milliseconds                1/1068 milliseconds
     * ADVERTISE_MODE_BALANCED             1/400 milliseconds                 1/295 milliseconds
     * ADVERTISE_MODE_LOW_POWER            1/160 milliseconds                 1/142 milliseconds
     */
    public static AdvertiseSettings createAdvSettings(boolean connectable, int timeoutMillis) {
        //設定廣播的模式,應該是跟功耗相關
        AdvertiseSettings.Builder mSettingsbuilder = new AdvertiseSettings.Builder();
        mSettingsbuilder.setAdvertiseMode(AdvertiseSettings.ADVERTISE_MODE_BALANCED);
        mSettingsbuilder.setConnectable(connectable);
        mSettingsbuilder.setTimeout(timeoutMillis);
        mSettingsbuilder.setTxPowerLevel(AdvertiseSettings.ADVERTISE_TX_POWER_HIGH);
        AdvertiseSettings mAdvertiseSettings = mSettingsbuilder.build();
        if (mAdvertiseSettings == null) {
            Toast.makeText(Utils.getContext(), "mAdvertiseSettings == null", Toast.LENGTH_LONG).show();
            Log.e(TAG, "mAdvertiseSettings == null");
        }
        return mAdvertiseSettings;
    }

    //設定一下FMP廣播資料
    public static AdvertiseData createAdvertiseData() {
        AdvertiseData.Builder mDataBuilder = new AdvertiseData.Builder();
        // mDataBuilder.addServiceUuid(ParcelUuid.fromString(HEART_RATE_SERVICE));
        //新增的資料
        mDataBuilder.addServiceData(ParcelUuid.fromString(HEART_RATE_SERVICE), "eeeeeeeeee".getBytes());
        AdvertiseData mAdvertiseData = mDataBuilder.build();
        if (mAdvertiseData == null) {
            Toast.makeText(Utils.getContext(), "mAdvertiseSettings == null", Toast.LENGTH_LONG).show();
            Log.e(TAG, "mAdvertiseSettings == null");
        }
        return mAdvertiseData;
    }

   //登出
  @Override
    protected void onDestroy() {
    super.onDestroy();
    Toast.makeText(Utils.getContext(), "停止廣播", Toast.LENGTH_LONG).show();
    Log.e(TAG, "停止廣播");
    //停止藍芽廣播
    stopAdvertise();
}
private void stopAdvertise() {
if (mBluetoothLeAdvertiser != null) { 
mBluetoothLeAdvertiser.stopAdvertising(mAdvertiseCallback);  
 mBluetoothLeAdvertiser = null; 
Log.e(TAG, "停止廣播");
}}
//新增許可權
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />

//收工

demo下載地址      https://download.csdn.net/download/qq_36665856/10396723