android中将蓝牙设置为始终可发现模式

avatar
作者
猴君
阅读量:0

 BlueAlwaysDiscoverableReceiver.java

package com.ks.xybase.receiver;  import android.bluetooth.BluetoothAdapter; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter;   import com.ks.xybase.utils.L;  import java.lang.reflect.Method; import java.util.Objects;  //蓝牙设置为始终可发现模式 public class BlueAlwaysDiscoverableReceiver extends BroadcastReceiver {     private static final String TAG = "BlueAlwaysDiscoverableR";     private Context mContext;     private BluetoothAdapter mBluetoothAdapter;     private IntentFilter mIntentFilter;      public BlueAlwaysDiscoverableReceiver(Context context) {         mContext = context;         mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();         mIntentFilter = new IntentFilter();         mIntentFilter.addAction(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED);     }      public void start() {         mContext.registerReceiver(this, mIntentFilter);         setBlueCanVisible();     }      public void stop() {         mContext.unregisterReceiver(this);     }      @Override     public void onReceive(Context context, Intent intent) {         String action = intent.getAction();         if (!Objects.equals(action, BluetoothAdapter.ACTION_SCAN_MODE_CHANGED)) {             return;         }         setBlueCanVisible();     }      private void setBlueCanVisible() {         try {             Method setScanModeMethod = BluetoothAdapter.class.getMethod("setScanMode", int.class);             setScanModeMethod.setAccessible(true);             setScanModeMethod.invoke(mBluetoothAdapter, BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE);         } catch (Exception e) {             L.d(TAG, "error when setBlueCanVisible,e==" + e.getMessage());         }     } } 

然后在activity中

private BlueAlwaysDiscoverableReceiver mBlueAlwaysDiscoverableReceiver;  protected void onCreate(Bundle savedInstanceState) {         super.onCreate(savedInstanceState);         setContentView(R.layout.activity_main);         //设置蓝牙为始终被发现模式         mBlueAlwaysDiscoverableReceiver = new BlueAlwaysDiscoverableReceiver(this);         mBlueAlwaysDiscoverableReceiver.start();     }   @Override     protected void onDestroy() {         mBlueAlwaysDiscoverableReceiver.stop();         super.onDestroy();     }  

广告一刻

为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!