I\'m trying to create a widget that contains a single ImageView which, when clicked, starts speech recognition application. I\'ve never worked with widgets and pending inten
This is fully functional, and it's based off the ListView widget in the Android SDK. It's not particularly for a widget, but I'm sure you can modify it so that it works for a widget.
Create an activity called SearchActivity:
// CustomSearch (View) & ISearch (Interface) are objects that I created and are irrelevant
public class SearchActivity extends AppCompatActivity implements ISearch
{
// Variables
private CustomSearch mSearchView;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
mSearchView = (CustomSearch)findViewById(R.id.search);
mSearchView.setPendingComponentName(getComponentName());
mSearchView.setSearchListener(this);
}
@Override
protected void onNewIntent(Intent intent)
{
if (Intent.ACTION_SEARCH.equals(intent.getAction()))
{
String query = intent.getStringExtra(SearchManager.QUERY);
Log.i("SEARCH >", "You said: " + query);
}
}
}
Add activity to the AndroidManifest.xml
In your custom Widget/View:
buttonVoice.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
// Get activity from either SearchableInfo or ComponentName
ComponentName searchActivity = mComponentName;
// Wrap component in intent
Intent queryIntent = new Intent(Intent.ACTION_SEARCH);
queryIntent.setComponent(searchActivity);
// Wrap query intent in pending intent
PendingIntent pending = PendingIntent.getActivity(getContext(), 0, queryIntent, PendingIntent.FLAG_ONE_SHOT);
// Create bundle now because if we wrap it in pending intent, it becomes immutable
Bundle queryExtras = new Bundle();
// Create voice intent
Intent voiceIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZER_SPEECH);
voiceIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
voiceIntent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Speak");
voiceIntent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, searchActivity
voiceIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// Wrap the pending intent & bundle inside the voice intent
voiceIntent.putExtra(RecognizerIntent.EXTRA_RESULTS_PENDINGINTENT, pending);
voiceIntent.putExtra(RecognizerIntent.EXTRA_RESULTS_PENDINGINTENT_BUNDLE, queryExtras);
// Start the voice search
getContext().startActivity(voiceIntent);
}
}