我需要在我的应用程序内知道蓝牙是打开还是关闭。或者,例如从OS设置下拉菜单中打开或关闭了蓝牙。我以为可以在“活动”中执行此操作onResume()
。但是事实证明,打开Android OS的设置“下拉菜单”(通过从屏幕顶部边缘用手指下拉来访问该菜单)时,活动不会暂停。
蓝牙可用或不可用时,我需要更新UI。
我可以注册一个回调(例如BroadcastReceiver
)或任何其他回调以让系统在蓝牙可用性发生变化时告诉我吗?
您可以使用意图过滤器注册接收器:
<receiver
android:name="com.example.BluetoothReceiver"
android:enabled="true">
<intent-filter>
<action android:name="android.bluetooth.adapter.action.STATE_CHANGED"/>
</intent-filter>
</receiver>
这是BroadcastReceiver:
public class BluetoothReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)) {
int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, -1);
switch (state){
case BluetoothAdapter.STATE_OFF:
//Indicates the local Bluetooth adapter is off.
break;
case BluetoothAdapter.STATE_TURNING_ON:
//Indicates the local Bluetooth adapter is turning on. However local clients should wait for STATE_ON before attempting to use the adapter.
break;
case BluetoothAdapter.STATE_ON:
//Indicates the local Bluetooth adapter is on, and ready for use.
break;
case BluetoothAdapter.STATE_TURNING_OFF:
//Indicates the local Bluetooth adapter is turning off. Local clients should immediately attempt graceful disconnection of any remote links.
break;
}
}
}
};
或者,如果您想直接在活动中添加:
public class ExampleActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_example);
}
@Override
protected void onResume() {
super.onResume();
registerReceiver(mReceiver, new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED));
}
@Override
protected void onPause() {
super.onPause();
unregisterReceiver(mReceiver);
}
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)) {
int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, -1);
switch (state) {
case BluetoothAdapter.STATE_OFF:
//Indicates the local Bluetooth adapter is off.
break;
case BluetoothAdapter.STATE_TURNING_ON:
//Indicates the local Bluetooth adapter is turning on. However local clients should wait for STATE_ON before attempting to use the adapter.
break;
case BluetoothAdapter.STATE_ON:
//Indicates the local Bluetooth adapter is on, and ready for use.
break;
case BluetoothAdapter.STATE_TURNING_OFF:
//Indicates the local Bluetooth adapter is turning off. Local clients should immediately attempt graceful disconnection of any remote links.
break;
}
}
}
};
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句