Calling startIntentSenderForResult from Fragment (Android Billing v3)

前端 未结 11 1175
广开言路
广开言路 2020-11-29 02:46

The new Android Billing v3 documentation and helper code uses startIntentSenderForResult() when launching a purchase flow. I want to start a purchase flow (and

11条回答
  •  半阙折子戏
    2020-11-29 03:24

    Edit: android.support.v4.app.Fragment now contains a backwards compatible version of startIntentSenderForResult(), so this answer is obsolete.

    Old answer:

    As of support library 23.2.0, modifying the requestCode no longer works: FragmentActivity now keeps track of the requests made by its fragments. I added this method to the FragmentActivity that was hosting the Fragment (code based on FragmentActivity.startActivityFromFragment(Fragment, Intent, int, Bundle)):

    public void startIntentSenderFromFragment(Fragment fragment, IntentSender intent, int requestCode, @Nullable Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags) throws IntentSender.SendIntentException {
        if (requestCode == -1) {
            startIntentSenderForResult(intent, requestCode, fillInIntent, flagsMask, flagsValues, extraFlags);
            return;
        }
    
        if ((requestCode & 0xffff0000) != 0) {
            throw new IllegalArgumentException("Can only use lower 16 bits for requestCode");
        }
    
        try {
            Method method = FragmentActivity.class.getDeclaredMethod("allocateRequestIndex", Fragment.class);
            method.setAccessible(true);
            int requestIndex = (int) method.invoke(this, fragment);
            startIntentSenderForResult(intent, ((requestIndex + 1) << 16) + (requestCode & 0xffff), fillInIntent, flagsMask, flagsValues, extraFlags);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    

    When calling this, only the passed Fragment will receive the onActivityResult() call.

提交回复
热议问题