Parag Verma
Parag Verma

Reputation: 93

Google Speech to Text from Notification

I've created a sort of permanent notification, and my goal is like this

1) User taps on the notification
2) Google Speech to Text activity starts and takes voice input
3) The input is converted to text and and a new activity starts, which shows that text.

Here's what I've tried so far--

    NotificationCompat.Builder builder = new NotificationCompat.Builder(MainActivity.this)
            .setSmallIcon(android.R.drawable.ic_dialog_alert)
            .setContentTitle("Tap for voice input")
            .setContentText("Hi");

    Intent resultIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
    resultIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
            RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
    resultIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault());
    resultIntent.putExtra(RecognizerIntent.EXTRA_PROMPT,
            getString(R.string.speech_prompt));
    PendingIntent pendingIntent = PendingIntent.getActivity(MainActivity.this, 0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);
    builder.setContentIntent(pendingIntent);

    Notification notification = builder.build();
    notification.flags = Notification.FLAG_NO_CLEAR;

    NotificationManagerCompat notificationManager = NotificationManagerCompat.from(MainActivity.this);
    notificationManager.notify(0, notification);

Now I know that I can process the results of the recognizer Intent normally by using startActivityForResult(resultIntent, REQ_CODE_SPEECH_INPUT);, and processing it in my activity.

but I have to pass my intent into a pendingIntent for the notification.

Any way I can achieve this?

Edit 1:

I can start a new activity, and then open voice Google voice prompt, but I want the converted string to be passed to my activity before it starts, like with an extra parameter in an intent...

Upvotes: 2

Views: 341

Answers (1)

Bö macht Blau
Bö macht Blau

Reputation: 13019

Use an "invisible" Activity as mediator. It's possible to have Activities without UI, see for example this SO post by Emanuel Moecklin. So you can modify the flow of your app like this:

  • User taps on the notification
  • Activity without UI starts and calls startActivityForResult() to obtain the result for the STT conversion
  • Google Speech to Text Activity starts and takes voice input
  • The input is converted to text and sent as result to the UI-less Activity
  • ... which in turn starts a new Activity which shows that text.

Upvotes: 2

Related Questions