How to make RecognizerIntent start different Activity that if was started from?

185 views Asked by At

In my application Activity A uses startActivityForResult to send a RecognizerIntent. Is it possible to tell it give results back to Activity B without going back through Activity A?

2

There are 2 answers

1
Tony J Huang On

PendingIntents are not meant to have results passed back to the caller, so that's out.

If ActivityB is behind ActivityA in the backstack, simply do this:

ActivityA {
    @Override
    public void onActivityResult (int requestCode, int resultCode, Intent data) {
        setResult(resultCode, data);
        finish();
    }
}

This will pass to ActivityB whatever data the RecognizerIntent Activity passed back to ActivityA.

If ActivityB is a separate Activity that you want to start when the RecognizerIntent Activity is completed:

ActivityA {
    @Override
    public void onActivityResult (int requestCode, int resultCode, Intent data) {
        Intent intent = new Intent(this, ActivityB.class);
        intent.putExtras(data);
        startActivity(intent);
    }
}

That will start ActivityB from ActivityA, passing the data through as a bundle that can be retrieved via getIntent().get___Extra(String key)

3
Nana Ghartey On

Using a PendingIntent you can push the results to activity B without returning to A:

In Activity A:

Intent activityIntent = new Intent(this, ActivityB.class);
PendingIntent resPendingIntent = PendingIntent.getActivity(this, 0, activityIntent, 0);

Intent speechRecIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
speechRecIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
speechRecIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
speechRecIntent.putExtra(RecognizerIntent.EXTRA_RESULTS_PENDINGINTENT, resPendingIntent);


PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, speechRecIntent, 0);
    try {
    pendingIntent.send();
} catch (PendingIntent.CanceledException e) {
    e.printStackTrace();
}

Then in Activity B, you get get the results in it's onCreate():

Intent intent = getIntent();
if(intent.hasExtra(RecognizerIntent.EXTRA_RESULTS);
ArrayList<String> speechRecResults = intent.getStringArrayList(RecognizerIntent.EXTRA_RESULTS);