I wanted to create google like widget. I tried zorglub76 solution, but I wasn't able to get voice the result...
I solved it by creating a dummy transparrent activity that handles the voice recognition end-to-end.
It work as follows: Widget->VoiceRecognitionStarterActivity->RecognizerIntent->VoiceRecognitionStarterActivity.onActivityResult.
My widget class:
public class MyWidgetProvider extends AppWidgetProvider {
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager,int[] appWidgetIds) {
// Get all ids
ComponentName thisWidget = new ComponentName(context, MyWidgetProvider.class);
int[] allWidgetIds = appWidgetManager.getAppWidgetIds(thisWidget);
for (int widgetId : allWidgetIds) {
RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.widget_layout);
Intent activityIntent = new Intent(context, VoiceRecognitionStarterActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, activityIntent, 0);
remoteViews.setOnClickPendingIntent(R.id.mic_image, pendingIntent);
activityIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(context.getString(R.string.search_url)));
pendingIntent = PendingIntent.getActivity(context, 0, activityIntent, 0);
remoteViews.setOnClickPendingIntent(R.id.search_box_image, pendingIntent);
appWidgetManager.updateAppWidget(widgetId, remoteViews);
}
}
}
My transparrent activity:
public class VoiceRecognitionStarterActivity extends Activity
{
private static final String TAG = "VoiceRecognitionStarterActivity";
private int SPEECH_REQUEST_CODE = 1;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sendRecognizeIntent();
}
private void sendRecognizeIntent()
{
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Speak to search");
intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 10);
startActivityForResult(intent, SPEECH_REQUEST_CODE);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (requestCode == SPEECH_REQUEST_CODE)
{
if (resultCode == RESULT_OK) {
Log.d(TAG, "result ok");
Intent searchIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(getString(R.string.search_url)));
startActivity(searchIntent);
finish();
} else {
Log.d(TAG, "result NOT ok");
finish();
}
}
super.onActivityResult(requestCode, resultCode, data);
}
}
To make the activity transparrent, see this post