我有一个应用程序,用于使用SPP协议对嵌入式系统进行蓝牙控制,该协议在棉花糖之前一直运行良好。如果启动应用程序时启用了蓝牙,那么一切都很好。我使用startActivityForResult()来提示用户允许蓝牙(如果尚未启用)。它过去一直阻塞直到给出结果为止,但是在棉花糖下,它会崩溃并立即崩溃,并出现空指针异常。我在onResume()中添加了一个“ hack”,通过未启用则返回来阻止它执行此操作,但是我想知道这是否是不正确的做法?
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btAdapter = BluetoothAdapter.getDefaultAdapter();
if (btAdapter == null) {
Toast.makeText(getApplicationContext(), "No bluetooth detected", Toast.LENGTH_SHORT).show();
finish();
} else {
if (!btAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, ENABLE_BT_REQUEST_CODE);
}
}
}
@Override
public void onResume() {
super.onResume();
/* This keeps from crashing immediately if BT not enabled */
if (!btAdapter.isEnabled()) {
return;
};
if (btAdapter.isDiscovering()) {
btAdapter.cancelDiscovery();
}
// Rest of code .......
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Check Result from turnOnBT()
if (requestCode == ENABLE_BT_REQUEST_CODE) {
if (resultCode == RESULT_CANCELED) {
Toast.makeText(getApplicationContext(), "Bluetooth must be enabled to continue", Toast.LENGTH_SHORT).show();
finish();
}
}
}