Launch intents

Various snippets for launching default apps, and more.

Check if an Intent can be handled

PackageManager manager = context.getPackageManager();
List<ResolveInfo> infos = manager.queryIntentActivities(intent, 0);
return infos.size() > 0;

Launch the default email app

The most robust way of sending emails is derived from this blog post. It works with both the native Gmail client and the Samsung mail client. We assume et_message is an EditText that contains the message.

val subject = ...
val address = getString(R.string.email_feedback)

// Replace newlines to make sure the message is not merged onto
// a single line in the mail client
val body = et_message.text.trim().toString().replace("\n", "<br>")

val intent = Intent(Intent.ACTION_SENDTO).apply {
    type = "message/rfc822"
    data = Uri.parse("mailto:$address?subject=$subject&body=$body")
    putExtra(Intent.EXTRA_EMAIL, arrayOf(address))
    putExtra(Intent.EXTRA_SUBJECT, subject)
    putExtra(Intent.EXTRA_TEXT, body)

This works well with this snippet to enable/disable the send button based on if there’s content in the EditText or not:

et_message.doOnTextChanged { _, _, _, _ ->
    bt_send.isEnabled = et_message.toString().isNotBlank()

Launch the browser or generic URL (to Play Store or whereever)

final Intent intent = new Intent(Intent.ACTION_VIEW);

Launch phone app / dialer

String uri = "tel:" + getString(R.string.phone_number);
// Use ACTION_CALL to call directly (requires 
// the android.permission.CALL_PHONE permission).
Intent intent = new Intent(Intent.ACTION_DIAL);

Launch the Play Store on the phone from an Android Wear app

This is only possible if the Wear app is a system app!

To test this from the shell, execute:

adb -e shell am start -a -e package_name com.pixplicity.example.my_app
     * Opens the Play Store on the phone, deep-linking to an app.
     * <strong>Only works when the app is installed as a system app!</strong> and
     * <strong>assumes the Play Store is present</strong>, so check for its availability using
     * {@link #getPlayStoreAvailability(Context)} first.
     * @param context The Context used to send the intent
     * @param newTask If the activity should be started as a new task. <strong>This must be
     *                {@code true} when the given Context is not an Activity!</strong>
    public static void launchPlayStore(Context context, boolean newTask) {
        Intent intent = new Intent("");
        intent.putExtra("package_name", "com.pixplicity.example.my_app");
        if (newTask) {