Android 等待 activity 结果

Android wait for activity result

我不知道如何等待用户选择是否启用蓝牙。如果应用程序在未启用蓝牙的情况下启动,它会崩溃,因为我没有等待此行的结果:

mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (!mBluetoothAdapter.isEnabled()) {
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBtIntent, 1);
        }

如何等到用户选择是或否才启用蓝牙? -谢谢

您必须按照本文所述重写 onActivityResult。

http://developer.android.com/training/basics/intents/result.html

这是一般流程:

  1. 您开始另一个 activity 以达到您发布的时尚效果
  2. 一旦调用 activity 完成,它应该 return 通过 onActivityResult 方法向调用 activity 传递结果。

ex调用该方法后,您应该检查结果或检查蓝牙是否打开。并根据您现在掌握的信息继续执行。

文章中的代码片段:

static final int PICK_CONTACT_REQUEST = 1;  // The request code

private void pickContact() {
   Intent pickContactIntent = new Intent(Intent.ACTION_PICK, Uri.parse("content://contacts"));
   pickContactIntent.setType(Phone.CONTENT_TYPE); // Show user only contacts w/ phone numbers
   startActivityForResult(pickContactIntent, PICK_CONTACT_REQUEST);
}


@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// Check which request we're responding to
 if (requestCode == PICK_CONTACT_REQUEST) {
    // Make sure the request was successful
    if (resultCode == RESULT_OK) {
        // The user picked a contact.
        // The Intent's data Uri identifies which contact was selected.

        // Do something with the contact here (bigger example below)
    }
 }
}