androidbundleandroid-pendingintentrecognizer-intent

RecognizerIntent: how to add a bundle to a pending intent


I am implementing an activity that responds to the RecognizerIntent. Among others this activity must handle two incoming extras that specify a pending intent and its extras-bundle:

Paraphrasing the documentation:

I have been looking in vain for sample code that would demonstrate the following.

What is the best way of extracting a PendingIntent from a bundle?

Should I do:

(PendingIntent)
        extras.getParcelable(RecognizerIntent.EXTRA_RESULTS_PENDINGINTENT)

How to add extras to the set of existing extras of a PendingIntent?

How to launch the modified PendingIntent?


Solution

  • These are my current answers to these questions. It works like this in a number of Google apps (Maps, Docs, YouTube, Listen) which all pass the PendingIntent to the RecognizerIntent when you perform the search via the microphone button. I am unsure though if this is the best (or most general) way of doing it. Any comments are welcome.

    What is the best way of extracting a PendingIntent from a bundle?

    Parcelable extraResultsPendingIntentAsParceable =
               bundle.getParcelable(RecognizerIntent.EXTRA_RESULTS_PENDINGINTENT);
    if (extraResultsPendingIntentAsParceable != null) {
        if (extraResultsPendingIntentAsParceable instanceof PendingIntent) {
            mExtraResultsPendingIntent =
                             (PendingIntent) extraResultsPendingIntentAsParceable;
        } else {
            // Report an error
        }
    }
    
    mExtraResultsPendingIntentBundle =
              bundle.getBundle(RecognizerIntent.EXTRA_RESULTS_PENDINGINTENT_BUNDLE);
    

    How to add extras to the set of existing extras of a PendingIntent?

    Here we just create a new intent and put all the required extras into it.

    if (mExtraResultsPendingIntentBundle == null) {
        mExtraResultsPendingIntentBundle = new Bundle();
    }               
    Intent intent = new Intent(); 
    intent.putExtras(mExtraResultsPendingIntentBundle);
    // Unsure about the following line...
    // Should I use another name for the extra data (instead of SearchManager.QUERY)
    intent.putExtra(SearchManager.QUERY, speechRecognitionResult);
    

    How to launch the modified PendingIntent?

    We send off the PendingIntent giving it the new intent (with the new extras) as an argument.

    try {           
        mExtraResultsPendingIntent.send(this, 1234, intent);
    } catch (CanceledException e) {
        // Handle exception
    }