Android等待活动结果

时间:2015-04-17 18:04:26

标签: android bluetooth

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

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

我该如何等到用户选择是或否来启用蓝牙? -Thanks

1 个答案:

答案 0 :(得分:2)

您必须覆盖onActivityResult,如本文所述。

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

这是一般流程:

  1. 您为发布时尚的结果开始另一项活动
  2. 一旦被调用的活动完成,它应该通过onActivityResult方法将结果返回给调用活动。
  3. 您应检查结果或检查是否在调用该方法后打开蓝牙。并根据您现有的信息继续执行。

    文章中的代码段:

    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)
        }
     }
    }