Example usage for android.content Intent resolveActivity

List of usage examples for android.content Intent resolveActivity

Introduction

In this page you can find the example usage for android.content Intent resolveActivity.

Prototype

public ComponentName resolveActivity(@NonNull PackageManager pm) 

Source Link

Document

Return the Activity component that should be used to handle this intent.

Usage

From source file:de.grobox.blitzmail.NotificationHandlerActivity.java

@Override
protected void onNewIntent(Intent intent) {
    Bundle extras = intent.getExtras();//from  w w  w  .j  a va  2s.c  o m

    // show dialog for server errors
    if (extras != null && extras.getString("ContentTitle").equals(getString(R.string.error))) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);

        builder.setTitle(getString(R.string.app_name) + " - " + getString(R.string.error));
        builder.setMessage(extras.getString("ContentText"));
        builder.setIcon(android.R.drawable.ic_dialog_alert);

        // Add the buttons
        builder.setNegativeButton(getResources().getString(R.string.dismiss),
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        deleteMail();
                        // User clicked Cancel button, close this Activity
                        finish();
                    }
                });
        builder.setNeutralButton(getResources().getString(R.string.send_later),
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        // User clicked Cancel button
                        if (BuildConfig.PRO) {
                            // close this Activity
                            finish();
                        } else {
                            AlertDialog.Builder builder = new AlertDialog.Builder(context);

                            builder.setTitle(getString(R.string.app_name));
                            builder.setMessage(getString(R.string.error_lite_version));
                            builder.setIcon(android.R.drawable.ic_dialog_info);

                            // Add the buttons
                            builder.setPositiveButton(android.R.string.ok,
                                    new DialogInterface.OnClickListener() {
                                        public void onClick(DialogInterface lite_dialog, int id) {
                                            Uri uri = Uri.parse(
                                                    "https://play.google.com/store/apps/details?id=de.grobox.blitzmail.pro");
                                            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                                            if (intent.resolveActivity(getPackageManager()) != null) {
                                                startActivity(intent);
                                            }
                                            lite_dialog.dismiss();
                                            finish();
                                        }
                                    });
                            builder.setNegativeButton(android.R.string.cancel,
                                    new DialogInterface.OnClickListener() {
                                        public void onClick(DialogInterface lite_dialog, int id) {
                                            lite_dialog.dismiss();
                                            finish();
                                        }
                                    });

                            // Create and show the AlertDialog
                            AlertDialog lite_dialog = builder.create();
                            lite_dialog.setCanceledOnTouchOutside(false);
                            lite_dialog.show();
                        }
                    }
                });
        builder.setPositiveButton(getResources().getString(R.string.try_again),
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        // Prepare start of new activity
                        Intent intent = new Intent(context, SendActivity.class);
                        intent.setAction("BlitzMailReSend");
                        intent.putExtra("mail", mMail.toString());
                        finish();

                        startActivity(intent);
                    }
                });

        // Create and show the AlertDialog
        AlertDialog dialog = builder.create();
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();
    } else {
        // close activity
        finish();
    }
}

From source file:com.tomer.alwayson.SettingsFragment.java

@Override
public boolean onPreferenceChange(final Preference preference, Object o) {
    if (preference.getKey().equals("watchface_clock")) {
        int value = Integer.parseInt((String) o);
        if (value > 2) {
            if (Globals.ownedItems != null) {
                if (Globals.ownedItems.size() > 0) {
                    return true;
                } else {
                    PreferencesActivity.quicklyPromptToSupport(getActivity(), Globals.mService, rootView);
                    return false;
                }/*from  w  w w. j ava  2 s .c o  m*/
            } else {
                PreferencesActivity.quicklyPromptToSupport(getActivity(), Globals.mService, rootView);
            }
        } else {
            return true;
        }
    }

    prefs.apply();
    Utils.logDebug("Preference change", preference.getKey() + " Value:" + o.toString());

    if (preference.getKey().equals("notifications_alerts")) {
        if ((boolean) o)
            return checkNotificationsPermission(context, true);
        return true;
    }
    if (preference.getKey().equals("persistent_notification") && !(boolean) o) {
        Snackbar.make(rootView, R.string.warning_1_harm_performance, 10000)
                .setAction(R.string.action_revert, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        ((CheckBoxPreference) preference).setChecked(true);
                        restartService();
                    }
                }).show();
        restartService();
    }
    if (preference.getKey().equals("enabled")) {
        restartService();
    }
    if (preference.getKey().equals("proximity_to_lock")) {
        if (Shell.SU.available() || Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
            return true;
        else {
            DevicePolicyManager mDPM = (DevicePolicyManager) context
                    .getSystemService(Context.DEVICE_POLICY_SERVICE);
            final ComponentName mAdminName = new ComponentName(context, DAReceiver.class);
            if ((mDPM != null && mDPM.isAdminActive(mAdminName))) {
                return true;
            }
            new AlertDialog.Builder(getActivity())
                    .setTitle(getString(android.R.string.dialog_alert_title) + "!")
                    .setMessage(getString(R.string.warning_7_disable_fingerprint))
                    .setPositiveButton(getString(android.R.string.yes), (dialogInterface, i) -> {
                        Intent intent = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);
                        intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, mAdminName);
                        intent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION,
                                getString(R.string.settings_proximity));
                        startActivityForResult(intent, DEVICE_ADMIN_REQUEST_CODE);
                    }).setNegativeButton(getString(android.R.string.no), (dialogInterface, i) -> {
                        dialogInterface.dismiss();
                    }).show();
            return false;
        }
    }
    if (preference.getKey().equals("startafterlock") && !(boolean) o) {
        Snackbar.make(rootView, R.string.warning_4_device_not_secured, 10000)
                .setAction(R.string.action_revert, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        ((CheckBoxPreference) preference).setChecked(true);
                    }
                }).show();
    }
    if (preference.getKey().equals("doze_mode") && (boolean) o) {
        if (Shell.SU.available()) {
            if (!DozeManager.isDumpPermissionGranted(context))
                DozeManager.grantPermission(context, "android.permission.DUMP");
            if (!DozeManager.isDevicePowerPermissionGranted(context))
                DozeManager.grantPermission(context, "android.permission.DEVICE_POWER");
            return true;
        }
        Snackbar.make(rootView, R.string.warning_11_no_root, Snackbar.LENGTH_LONG).show();
        return false;
    }
    if (preference.getKey().equals("camera_shortcut") || preference.getKey().equals("google_now_shortcut")) {
        try {
            if (!hasUsageAccess()) {
                Intent intent = new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS);
                PackageManager packageManager = getActivity().getPackageManager();
                if (intent.resolveActivity(packageManager) != null) {
                    startActivity(intent);
                } else {
                    Toast.makeText(context,
                            "Please grant usage access permission manually for the app, your device can't do it automatically.",
                            Toast.LENGTH_LONG).show();
                }
                return false;
            }
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
    }
    if (preference.getKey().equals("battery_saver"))
        if ((boolean) o) {
            ((TwoStatePreference) findPreference("doze_mode")).setChecked(true);
            setUpBatterySaverPermission();
        }
    return true;
}

From source file:org.alfresco.mobile.android.application.fragments.user.UserProfileFragment.java

public static void actionAddContact(FragmentActivity activity, Person member) {
    if (member != null) {
        final Intent intent = new Intent(Intent.ACTION_INSERT);
        intent.setType(ContactsContract.Contacts.CONTENT_TYPE);

        // ABOUT Information
        intent.putExtra(ContactsContract.Intents.Insert.NAME,
                member.getLastName() + " " + member.getFirstName());

        // JOB TITLE
        intent.putExtra(ContactsContract.Intents.Insert.JOB_TITLE, member.getJobTitle());

        // CONTACT PHONE
        intent.putExtra(ContactsContract.Intents.Insert.PHONE, member.getTelephoneNumber());
        intent.putExtra(ContactsContract.Intents.Insert.PHONE_ISPRIMARY, true);
        intent.putExtra(ContactsContract.Intents.Insert.PHONE_TYPE,
                ContactsContract.CommonDataKinds.Phone.TYPE_MAIN);
        intent.putExtra(ContactsContract.Intents.Insert.SECONDARY_PHONE, member.getMobileNumber());
        intent.putExtra(ContactsContract.Intents.Insert.SECONDARY_PHONE_TYPE,
                ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE);

        // CONTACT EMAIL
        intent.putExtra(ContactsContract.Intents.Insert.EMAIL, member.getEmail());
        intent.putExtra(ContactsContract.Intents.Insert.EMAIL_TYPE,
                ContactsContract.CommonDataKinds.Email.TYPE_WORK);

        // CONTACT IM
        if (member.getSkypeId() != null && member.getSkypeId().length() > 0) {
            intent.putExtra(ContactsContract.Intents.Insert.IM_HANDLE, member.getSkypeId());
            intent.putExtra(ContactsContract.Intents.Insert.IM_PROTOCOL,
                    ContactsContract.CommonDataKinds.Im.PROTOCOL_SKYPE);
        }//from ww w . j  av  a2 s .  co  m
        if (member.getGoogleId() != null && member.getGoogleId().length() > 0) {
            intent.putExtra(ContactsContract.Intents.Insert.IM_HANDLE, member.getGoogleId());
            intent.putExtra(ContactsContract.Intents.Insert.IM_PROTOCOL,
                    ContactsContract.CommonDataKinds.Im.PROTOCOL_GOOGLE_TALK);
        } else if (member.getInstantMessageId() != null && member.getInstantMessageId().length() > 0) {
            intent.putExtra(ContactsContract.Intents.Insert.IM_HANDLE, member.getInstantMessageId());
        }

        // COMPANY DETAILS
        intent.putExtra(ContactsContract.Intents.Insert.COMPANY, member.getCompany().getName());

        intent.putExtra(ContactsContract.Intents.Insert.SECONDARY_EMAIL, member.getCompany().getEmail());
        intent.putExtra(ContactsContract.Intents.Insert.SECONDARY_EMAIL_TYPE,
                ContactsContract.CommonDataKinds.Email.TYPE_OTHER);

        intent.putExtra(ContactsContract.Intents.Insert.TERTIARY_PHONE,
                member.getCompany().getTelephoneNumber());
        intent.putExtra(ContactsContract.Intents.Insert.TERTIARY_PHONE_TYPE,
                ContactsContract.CommonDataKinds.Phone.TYPE_COMPANY_MAIN);

        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

        try {
            if (intent.resolveActivity(activity.getPackageManager()) == null) {
                AlfrescoNotificationManager.getInstance(activity).showAlertCrouton((FragmentActivity) activity,
                        activity.getString(R.string.feature_disable));
                return;
            }

            activity.startActivity(Intent.createChooser(intent, activity.getString(R.string.contact_add)));

            AnalyticsHelper.reportOperationEvent(activity, AnalyticsManager.CATEGORY_USER,
                    AnalyticsManager.ACTION_ADD_CONTACT, AnalyticsManager.LABEL_CONTACT, 1, false);
        } catch (ActivityNotFoundException e) {

        }
    }
}

From source file:com.farmerbb.notepad.fragment.NoteEditFragment.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Hide soft keyboard
    InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
    imm.hideSoftInputFromWindow(getActivity().findViewById(R.id.editText1).getWindowToken(), 0);

    switch (item.getItemId()) {
    case android.R.id.home:
        // Override default Android "up" behavior to instead mimic the back button
        getActivity().onBackPressed();/* w w w  . j av  a2  s .c  om*/
        return true;

    // Save button
    case R.id.action_save:
        // Get current note contents from EditText
        noteContents = getActivity().findViewById(R.id.editText1);
        contents = noteContents.getText().toString();

        // If EditText is empty, show toast informing user to enter some text
        if (contents.equals(""))
            showToast(R.string.empty_note);
        else if (directEdit)
            getActivity().onBackPressed();
        else {
            // If no changes were made since last save, switch back to NoteViewFragment
            if (contentsOnLoad.equals(noteContents.getText().toString())) {
                Bundle bundle = new Bundle();
                bundle.putString("filename", filename);

                Fragment fragment = new NoteViewFragment();
                fragment.setArguments(bundle);

                getFragmentManager().beginTransaction().replace(R.id.noteViewEdit, fragment, "NoteViewFragment")
                        .commit();
            } else {
                SharedPreferences pref = getActivity().getSharedPreferences(
                        getActivity().getPackageName() + "_preferences", Context.MODE_PRIVATE);
                if (pref.getBoolean("show_dialogs", true)) {
                    // Show save button dialog
                    listener.showSaveButtonDialog();
                } else {
                    try {
                        Intent intent = new Intent();
                        intent.putExtra(Intent.EXTRA_TEXT, noteContents.getText().toString());
                        this.getActivity().setResult(Activity.RESULT_OK, intent);
                        saveNote();

                        if (listener.isShareIntent())
                            getActivity().finish();
                        else {
                            Bundle bundle = new Bundle();
                            bundle.putString("filename", filename);

                            Fragment fragment = new NoteViewFragment();
                            fragment.setArguments(bundle);

                            getFragmentManager().beginTransaction()
                                    .replace(R.id.noteViewEdit, fragment, "NoteViewFragment").commit();
                        }
                    } catch (IOException e) {
                        // Show error message as toast if file fails to save
                        showToast(R.string.failed_to_save);
                    }
                }
            }
        }
        return true;

    // Delete button
    case R.id.action_delete:
        listener.showDeleteDialog();
        return true;

    // Share menu item
    case R.id.action_share:
        // Set current note contents to a String
        contents = noteContents.getText().toString();

        // If EditText is empty, show toast informing user to enter some text
        if (contents.equals(""))
            showToast(R.string.empty_note);
        else {
            // Send a share intent
            Intent intent = new Intent();
            intent.setAction(Intent.ACTION_SEND);
            intent.putExtra(Intent.EXTRA_TEXT, contents);
            intent.setType("text/plain");

            // Verify that the intent will resolve to an activity, and send
            if (intent.resolveActivity(getActivity().getPackageManager()) != null)
                startActivity(Intent.createChooser(intent, getResources().getText(R.string.send_to)));
        }

        return true;

    // Export menu item
    case R.id.action_export:
        // Set current note contents to a String
        contents = noteContents.getText().toString();

        // If EditText is empty, show toast informing user to enter some text
        if (contents.equals(""))
            showToast(R.string.empty_note);
        else {
            String currentFilename = filename;
            filename = "exported_note";

            try {
                saveNote();
            } catch (IOException e) {
                /* Gracefully fail */ }

            filename = currentFilename;

            listener.exportNote("exported_note");
        }

        return true;

    // Print menu item
    case R.id.action_print:
        // Set current note contents to a String
        contents = noteContents.getText().toString();

        // If EditText is empty, show toast informing user to enter some text
        if (contents.equals(""))
            showToast(R.string.empty_note);
        else
            listener.printNote(contents);

        return true;

    default:
        return super.onOptionsItemSelected(item);
    }
}

From source file:org.kontalk.ui.ComposeMessageFragment.java

public void viewContact() {
    if (mConversation != null) {
        Contact contact = mConversation.getContact();
        if (contact != null) {
            Uri uri = contact.getUri();//from w  ww .  j av a 2 s. c  o m
            if (uri != null) {
                Intent i = new Intent(Intent.ACTION_VIEW, uri);
                if (i.resolveActivity(getActivity().getPackageManager()) != null) {
                    startActivity(i);
                } else {
                    // no contacts app found (crap device eh?)
                    Toast.makeText(getActivity(), R.string.err_no_contacts_app, Toast.LENGTH_LONG).show();
                }
            } else {
                // no contact found
                Toast.makeText(getActivity(), R.string.err_no_contact, Toast.LENGTH_SHORT).show();
            }
        }
    }
}

From source file:ca.ualberta.cs.drivr.RequestsListAdapter.java

/**
 * Called when the view holder is wants to bind the request at a certain position in the list.
 * @param viewHolder/*  w w  w  .  j a v a 2s . c  om*/
 * @param position
 */
@Override
public void onBindViewHolder(final RequestsListAdapter.ViewHolder viewHolder, final int position) {
    final Request request = requestsToDisplay.get(position);

    // Get the views to update
    final TextView otherUserNameTextView = viewHolder.otherUserNameTextView;
    final TextView descriptionTextView = viewHolder.descriptionTextView;
    final TextView fareTextView = viewHolder.fareTextView;
    final TextView routeTextView = viewHolder.routeTextView;
    final TextView statusTextView = viewHolder.statusTextView;
    final ImageView callImageView = viewHolder.callImageView;
    final ImageView emailImageView = viewHolder.emailImageView;
    final ImageView checkImageView = viewHolder.checkMarkImageView;
    final ImageView deleteImageView = viewHolder.xMarkImageView;

    // Todo Hide Image Views until correct Request State
    if (request.getRequestState() != RequestState.CONFIRMED) {
        checkImageView.setVisibility(View.INVISIBLE);
    }

    if (request.getRequestState() != RequestState.PENDING) {
        deleteImageView.setVisibility(View.INVISIBLE);
    }

    // Show the other person's name
    final DriversList drivers = request.getDrivers();

    // Get the username of the other user
    if (userManager.getUserMode() == UserMode.RIDER) {
        final String multipleDrivers = "Multiple Drivers Accepted";
        final String driverUsername = drivers.size() == 1 ? drivers.get(0).getUsername() : "No Driver Yet";
        otherUserNameTextView.setText(drivers.size() > 1 ? multipleDrivers : driverUsername);
    } else {
        otherUserNameTextView.setText(request.getRider().getUsername());
    }

    // If the request has a description, show it. Otherwise, hide te description
    if (Strings.isNullOrEmpty(request.getDescription()))
        descriptionTextView.setVisibility(View.GONE);
    else
        descriptionTextView.setText(request.getDescription());

    // Show the fare
    fareTextView.setText("$" + request.getFareString());

    // Show the route
    routeTextView.setText(request.getRoute());

    // Driver User
    otherUserNameTextView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            final String otherUsername = otherUserNameTextView.getText().toString();
            // there exists drivers
            if (otherUsername != "No Driver Yet") {
                if (otherUsername != "Multiple Drivers Accepted") {
                    Gson gson = new GsonBuilder().registerTypeAdapter(Uri.class, new UriSerializer()).create();

                    ElasticSearch elasticSearch = new ElasticSearch(
                            UserManager.getInstance().getConnectivityManager());
                    User user = elasticSearch.loadUser(otherUsername);

                    String driverString = gson.toJson(user, User.class);
                    Intent intent = new Intent(context, DriverProfileActivity.class);
                    intent.putExtra(DriverProfileActivity.DRIVER, driverString);
                    context.startActivity(intent);
                } else {
                    startMultipleDriverIntent(request);
                }
            }
        }
    });

    routeTextView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Gson gson = new GsonBuilder().registerTypeAdapter(Uri.class, new UriSerializer()).create();
            String requestString = gson.toJson(request, Request.class);
            Intent intent = new Intent(context, RequestActivity.class);
            intent.putExtra("UniqueID", "From_RequestListActivity");
            intent.putExtra(RequestActivity.EXTRA_REQUEST, requestString);
            context.startActivity(intent);
        }
    });

    // Show the status text
    statusTextView.setText(request.getRequestState().toString());

    // Add a listener to the call image
    callImageView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (drivers.size() == 0) {
                Toast.makeText(context, "No driver number available at this time", Toast.LENGTH_SHORT).show();

            }
            // Start Dialer
            else if (drivers.size() == 1) {
                Intent intent = new Intent(Intent.ACTION_CALL);
                String number;
                if (UserManager.getInstance().getUserMode().equals(UserMode.RIDER)) {
                    number = drivers.get(0).getPhoneNumber();
                } else {
                    number = request.getRider().getPhoneNumber();
                }
                number = "tel:" + number;
                intent.setData(Uri.parse(number));
                if (ActivityCompat.checkSelfPermission(context,
                        Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {

                    return;
                }
                context.startActivity(intent);

            } else {

                startMultipleDriverIntent(request);
            }
        }
    });

    // Add a listener to the email image
    emailImageView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (drivers.size() == 0) {
                Toast.makeText(context, "No driver email available at this time", Toast.LENGTH_SHORT).show();

            }
            //http://stackoverflow.com/questions/8701634/send-email-intent
            else if (drivers.size() == 1) {

                Intent intent = new Intent();
                ComponentName emailApp = intent.resolveActivity(context.getPackageManager());
                ComponentName unsupportedAction = ComponentName
                        .unflattenFromString("com.android.fallback/.Fallback");
                boolean hasEmailApp = emailApp != null && !emailApp.equals(unsupportedAction);
                String email;

                if (UserManager.getInstance().getUserMode().equals(UserMode.RIDER)) {
                    email = drivers.get(0).getEmail();
                } else {
                    email = request.getRider().getEmail();
                }
                String subject = "Drivr Request: " + request.getId();
                String body = "Drivr user " + drivers.get(0).getUsername();

                if (hasEmailApp) {
                    Intent emailIntent = new Intent(Intent.ACTION_SENDTO, Uri.parse("mailto:" + email));
                    emailIntent.putExtra(Intent.EXTRA_SUBJECT, subject);
                    emailIntent.putExtra(Intent.EXTRA_TEXT, body);
                    context.startActivity(Intent.createChooser(emailIntent, "Chooser Title"));
                } else {
                    Intent emailIntent = new Intent(Intent.ACTION_SENDTO, Uri.fromParts("mailto", email, null));
                    emailIntent.putExtra(Intent.EXTRA_SUBJECT, "");
                    emailIntent.putExtra(Intent.EXTRA_TEXT, "");
                    context.startActivity(Intent.createChooser(emailIntent, "Send email..."));
                }
            } else {
                startMultipleDriverIntent(request);

            }
        }
    });

    // Complete The Request
    checkImageView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(context, RequestCompletedActivity.class);
            intent.putExtra(RequestCompletedActivity.REQUEST_ID_EXTRA, request.getId());
            context.startActivity(intent);
        }
    });

    deleteImageView.setOnClickListener(new View.OnClickListener() {

        // Todo Delete the Request
        @Override
        public void onClick(View v) {
            v.getContext();
            ElasticSearch elasticSearch = new ElasticSearch(
                    (ConnectivityManager) v.getContext().getSystemService(Context.CONNECTIVITY_SERVICE));
            elasticSearch.deleteRequest(request.getId());
            UserManager userManager = UserManager.getInstance();
            userManager.getRequestsList().removeById(request);
            userManager.notifyObservers();
            requestsToDisplay.remove(request);
            notifyItemRemoved(viewHolder.getAdapterPosition());
        }
    });
}

From source file:com.android.launcher2.Launcher.java

private boolean updateVoiceSearchIcon(boolean searchVisible) {
    final View voiceButtonContainer = findViewById(R.id.voice_button_container);
    final View voiceButton = findViewById(R.id.voice_button);
    final View voiceButtonProxy = findViewById(R.id.voice_button_proxy);

    // We only show/update the voice search icon if the search icon is enabled as well
    final SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
    ComponentName globalSearchActivity = searchManager.getGlobalSearchActivity();

    ComponentName activityName = null;// ww w  . j a v a2  s .  c o m
    if (globalSearchActivity != null) {
        // Check if the global search activity handles voice search
        Intent intent = new Intent(RecognizerIntent.ACTION_WEB_SEARCH);
        intent.setPackage(globalSearchActivity.getPackageName());
        activityName = intent.resolveActivity(getPackageManager());
    }

    if (activityName == null) {
        // Fallback: check if an activity other than the global search activity
        // resolves this
        Intent intent = new Intent(RecognizerIntent.ACTION_WEB_SEARCH);
        activityName = intent.resolveActivity(getPackageManager());
    }
    if (searchVisible && activityName != null) {
        int coi = getCurrentOrientationIndexForGlobalIcons();
        sVoiceSearchIcon[coi] = updateButtonWithIconFromExternalActivity(R.id.voice_button, activityName,
                R.drawable.ic_home_voice_search_holo, TOOLBAR_VOICE_SEARCH_ICON_METADATA_NAME);
        if (sVoiceSearchIcon[coi] == null) {
            sVoiceSearchIcon[coi] = updateButtonWithIconFromExternalActivity(R.id.voice_button, activityName,
                    R.drawable.ic_home_voice_search_holo, TOOLBAR_ICON_METADATA_NAME);
        }
        if (voiceButtonContainer != null)
            voiceButtonContainer.setVisibility(View.VISIBLE);
        voiceButton.setVisibility(View.VISIBLE);
        if (voiceButtonProxy != null) {
            voiceButtonProxy.setVisibility(View.VISIBLE);
        }
        invalidatePressedFocusedStates(voiceButtonContainer, voiceButton);
        return true;
    } else {
        if (voiceButtonContainer != null)
            voiceButtonContainer.setVisibility(View.GONE);
        voiceButton.setVisibility(View.GONE);
        if (voiceButtonProxy != null) {
            voiceButtonProxy.setVisibility(View.GONE);
        }
        return false;
    }
}

From source file:com.android.launcher2.Launcher.java

/**
 * Sets the app market icon/* w  w  w. j a  v  a2 s .  co m*/
 */
private void updateAppMarketIcon() {
    final View marketButton = findViewById(R.id.market_button);
    Intent intent = new Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_APP_MARKET);
    // Find the app market activity by resolving an intent.
    // (If multiple app markets are installed, it will return the ResolverActivity.)
    ComponentName activityName = intent.resolveActivity(getPackageManager());
    if (activityName != null) {
        int coi = getCurrentOrientationIndexForGlobalIcons();
        mAppMarketIntent = intent;
        sAppMarketIcon[coi] = updateTextButtonWithIconFromExternalActivity(R.id.market_button, activityName,
                R.drawable.ic_launcher_market_holo, TOOLBAR_ICON_METADATA_NAME);
        marketButton.setVisibility(View.VISIBLE);
    } else {
        // We should hide and disable the view so that we don't try and restore the visibility
        // of it when we swap between drag & normal states from IconDropTarget subclasses.
        marketButton.setVisibility(View.GONE);
        marketButton.setEnabled(false);
    }
}

From source file:at.bitfire.davdroid.ui.StartupDialogFragment.java

@NonNull
@Override//  ww  w  . j  a  v a 2  s .c om
@TargetApi(Build.VERSION_CODES.M)
@SuppressLint("BatteryLife")
public Dialog onCreateDialog(Bundle savedInstanceState) {
    setCancelable(false);

    final ServiceDB.OpenHelper dbHelper = new ServiceDB.OpenHelper(getContext());

    Mode mode = Mode.valueOf(getArguments().getString(ARGS_MODE));
    switch (mode) {
    case BATTERY_OPTIMIZATIONS:
        return new AlertDialog.Builder(getActivity()).setTitle(R.string.startup_battery_optimization)
                .setMessage(R.string.startup_battery_optimization_message)
                .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                    }
                }).setNeutralButton(R.string.startup_battery_optimization_disable,
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                Intent intent = new Intent(
                                        android.provider.Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS,
                                        Uri.parse("package:" + BuildConfig.APPLICATION_ID));
                                getContext().startActivity(intent);
                            }
                        })
                .setNegativeButton(R.string.startup_dont_show_again, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Settings settings = new Settings(dbHelper.getWritableDatabase());
                        settings.putBoolean(HINT_BATTERY_OPTIMIZATIONS, false);
                    }
                }).create();

    case DEVELOPMENT_VERSION:
        return new AlertDialog.Builder(getActivity()).setIcon(R.mipmap.ic_launcher)
                .setTitle(R.string.startup_development_version)
                .setMessage(R.string.startup_development_version_message)
                .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                    }
                }).setNeutralButton(R.string.startup_development_version_give_feedback,
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                startActivity(new Intent(Intent.ACTION_VIEW,
                                        Constants.webUri.buildUpon().appendEncodedPath("forums/").build()));
                            }
                        })
                .create();

    case FDROID_DONATE:
        return new AlertDialog.Builder(getActivity()).setIcon(R.mipmap.ic_launcher)
                .setTitle(R.string.startup_donate).setMessage(R.string.startup_donate_message)
                .setPositiveButton(R.string.startup_donate_now, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        startActivity(new Intent(Intent.ACTION_VIEW,
                                Constants.webUri.buildUpon().appendEncodedPath("donate/").build()));
                    }
                }).setNegativeButton(R.string.startup_donate_later, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                    }
                }).create();

    case OPENTASKS_NOT_INSTALLED:
        StringBuilder builder = new StringBuilder(getString(R.string.startup_opentasks_not_installed_message));
        if (Build.VERSION.SDK_INT < 23)
            builder.append("\n\n").append(getString(R.string.startup_opentasks_reinstall_davdroid));
        return new AlertDialog.Builder(getActivity()).setIcon(R.drawable.ic_alarm_on_dark)
                .setTitle(R.string.startup_opentasks_not_installed).setMessage(builder.toString())
                .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                    }
                }).setNeutralButton(R.string.startup_opentasks_not_installed_install,
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                Intent intent = new Intent(Intent.ACTION_VIEW,
                                        Uri.parse("market://details?id=org.dmfs.tasks"));
                                if (intent.resolveActivity(getContext().getPackageManager()) != null)
                                    getContext().startActivity(intent);
                                else
                                    App.log.warning("No market app available, can't install OpenTasks");
                            }
                        })
                .setNegativeButton(R.string.startup_dont_show_again, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Settings settings = new Settings(dbHelper.getWritableDatabase());
                        settings.putBoolean(HINT_OPENTASKS_NOT_INSTALLED, false);
                    }
                }).create();
    }

    throw new IllegalArgumentException(/* illegal mode argument */);
}

From source file:com.ludoscity.findmybikes.activities.NearbyActivity.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {

    case R.id.settings_menu_item:
        Intent settingsIntent = new Intent(this, SettingsActivity.class);
        startActivityForResult(settingsIntent, SETTINGS_ACTIVITY_REQUEST_CODE);
        return true;

    case R.id.about_menu_item:
        new MaterialDialog.Builder(this)
                .title(getString(R.string.app_name) + "  " + getString(R.string.app_version_name)
                        + " 20152017     F8Full") //http://stackoverflow.com/questions/4471025/how-can-you-get-the-manifest-version-number-from-the-apps-layout-xml-variable-->
                .items(R.array.about_dialog_items)
                .icon(ContextCompat.getDrawable(NearbyActivity.this, R.drawable.logo_48dp)).autoDismiss(false)
                .itemsCallback(new MaterialDialog.ListCallback() {

                    @Override/*  ww  w  .  ja v a 2s. c  om*/
                    public void onSelection(MaterialDialog dialog, View view, int which, CharSequence text) {

                        Intent intent;

                        switch (which) {
                        case 0:
                            startActivity(Utils.getWebIntent(NearbyActivity.this, "http://www.citybik.es", true,
                                    text.toString()));
                            break;
                        case 1:
                            intent = new Intent(Intent.ACTION_VIEW);
                            intent.setData(Uri.parse("market://details?id=com.ludoscity.findmybikes"));
                            if (intent.resolveActivity(getPackageManager()) != null) {
                                startActivity(intent);
                            }
                            break;
                        case 2:
                            String url = "https://www.facebook.com/findmybikes/";
                            Uri uri;
                            try {
                                getPackageManager().getPackageInfo("com.facebook.katana", 0);
                                // http://stackoverflow.com/questions/24526882/open-facebook-page-from-android-app-in-facebook-version-v11
                                uri = Uri.parse("fb://facewebmodal/f?href=" + url);
                                intent = new Intent(Intent.ACTION_VIEW, uri);
                            } catch (PackageManager.NameNotFoundException e) {
                                intent = Utils.getWebIntent(NearbyActivity.this, url, true, text.toString());
                            }

                            //Seen ActivityNotFoundException in firebase cloud lab (FB package found but can't be launched)
                            if (intent.resolveActivity(getPackageManager()) == null)
                                intent = Utils.getWebIntent(NearbyActivity.this, url, true, text.toString());

                            startActivity(intent);

                            break;
                        case 3:
                            intent = new Intent(Intent.ACTION_SENDTO);
                            intent.setData(Uri.parse("mailto:")); // only email apps should handle this
                            intent.putExtra(Intent.EXTRA_EMAIL, new String[] { "ludos+findmybikesfeedback"
                                    + getString(R.string.app_version_name) + "@ludoscity.com" });
                            intent.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.feedback_subject));
                            if (intent.resolveActivity(getPackageManager()) != null) {
                                startActivity(intent);
                            }
                            break;
                        case 4:
                            new LicensesDialog.Builder(NearbyActivity.this).setNotices(R.raw.notices).build()
                                    .show();
                            break;
                        case 5:
                            intent = new Intent(NearbyActivity.this, WebViewActivity.class);
                            intent.putExtra(WebViewActivity.EXTRA_URL,
                                    "file:///android_res/raw/privacy_policy.html");
                            intent.putExtra(WebViewActivity.EXTRA_ACTIONBAR_SUBTITLE,
                                    getString(R.string.hashtag_privacy));
                            startActivity(intent);
                            break;
                        case 6:
                            try {
                                // get the Twitter app if possible
                                getPackageManager().getPackageInfo("com.twitter.android", 0);
                                intent = new Intent(Intent.ACTION_VIEW,
                                        Uri.parse("twitter://user?screen_name=findmybikesdata"));
                                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            } catch (PackageManager.NameNotFoundException e) {
                                // no Twitter app, revert to browser
                                intent = Utils.getWebIntent(NearbyActivity.this,
                                        "https://twitter.com/findmybikesdata", true, text.toString());
                            }

                            if (intent.resolveActivity(getPackageManager()) == null)
                                intent = Utils.getWebIntent(NearbyActivity.this,
                                        "https://twitter.com/findmybikesdata", true, text.toString());

                            startActivity(intent);

                            break;
                        case 7:
                            intent = new Intent(Intent.ACTION_VIEW,
                                    Uri.parse("https://github.com/f8full/ludOScity/tree/master/FindMyBikes"));
                            startActivity(intent);
                            break;

                        }

                    }
                }).show();

        return true;
    }
    return super.onOptionsItemSelected(item);
}