Example usage for android.content.pm PackageManager resolveActivity

List of usage examples for android.content.pm PackageManager resolveActivity

Introduction

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

Prototype

public abstract ResolveInfo resolveActivity(Intent intent, @ResolveInfoFlags int flags);

Source Link

Document

Determine the best action to perform for a given Intent.

Usage

From source file:com.oo58.game.texaspoker.AppActivity.java

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    //         this.getWindow().setFlags(FLAG_HOMEKEY_DISPATCHED, FLAG_HOMEKEY_DISPATCHED);//
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
    mContext = AppActivity.this;

    try {/*from www  .j av a  2 s.  c  o  m*/
        ApplicationInfo appInfo = this.getPackageManager().getApplicationInfo(getPackageName(),
                PackageManager.GET_META_DATA);
        String msg = appInfo.metaData.getString("data_Name");

        //         int channelid = Integer.parseInt(msg) ;
        //         
        //         System.out.println(channelid);

    } catch (NameNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    mAct = this;
    allContext = this.getApplicationContext();
    mTencent = Tencent.createInstance("1104823392", getApplicationContext());
    PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    mWakeLock = pm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK, "MyLock");
    mWakeLock.acquire();

    MobclickAgent.setDebugMode(false);
    MobclickAgent.updateOnlineConfig(this);
    AnalyticsConfig.enableEncrypt(true);

    checkUpdate();

    PackageManager pm2 = getPackageManager();
    homeInfo = pm2.resolveActivity(new Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_HOME), 0);

    mNetChecker.initAndRegListener(mContext);

    mWXPay.init(this);

    MobClickCppHelper.init(this);

    //      // logcatdebug
    //       XGPushConfig.enableDebug(this, true);
    //      // registerPush(getApplicationContext(), XGIOperateCallback)callback
    //      // registerPush(getApplicationContext(),account)
    //      // 
    //      // ApplicationContext
    //      Context context = getApplicationContext();
    //      XGPushManager.registerPush(context);    
    //       
    //      // 2.362
    //      Intent service = new Intent(context, XGPushService.class);
    //      context.startService(service);

    // API
    // registerPush(context,account)registerPush(context,account, XGIOperateCallback)accountAPPqqopenid
    // registerPush(context,"*")account="*"
    // unregisterPush(context)
    // setTag(context, tagName)
    // deleteTag(context, tagName)

    updateListViewReceiver = new MsgReceiver();
    IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction("com.oo58.game.texaspoker.activity.UPDATE_LISTVIEW");
    registerReceiver(updateListViewReceiver, intentFilter);

    XGPushManager.registerPush(getApplicationContext(), new XGIOperateCallback() {
        @Override
        public void onSuccess(Object data, int flag) {
            //                  Log.w(Constants.LogTag,
            //                        "+++ register push sucess. token:" + data);

        }

        @Override
        public void onFail(Object data, int errCode, String msg) {
            //                  Log.w(Constants.LogTag,
            //                        "+++ register push fail. token:" + data
            //                              + ", errCode:" + errCode + ",msg:"
            //                              + msg);

        }
    });

    //javajosnC++demo
    /*      JSONObject jsonObj = new JSONObject();  
            try {
             jsonObj.put("Int_att",25);
               jsonObj.put("String_att","str");//string  
               jsonObj.put("Double_att",12.25);//double  
               jsonObj.put("Boolean_att",true);//boolean  
          } catch (JSONException e) {
             // TODO Auto-generated catch block
             e.printStackTrace();
          }//int  
            
            PushJson(jsonObj.toString()) ;*/

}

From source file:com.air.mobilebrowser.BrowserActivity.java

/**
 * Determine if the application is set as the default
 * home./*from  ww  w  .  j av a2  s  . com*/
 * @return true if the default home package is the secure browser, false
 * otherwise.
 */
public boolean validateHomePackage() {
    Intent intent = new Intent(Intent.ACTION_MAIN);
    intent.addCategory(Intent.CATEGORY_HOME);

    PackageManager pm = getPackageManager();
    final ResolveInfo mInfo = pm.resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY);
    String homePackage = mInfo.activityInfo.packageName;
    return homePackage.equals(getPackageName());
}

From source file:com.farmerbb.taskbar.activity.ContextMenuActivity.java

@SuppressWarnings("deprecation")
private void generateMenu() {
    if (isStartButton) {
        addPreferencesFromResource(R.xml.pref_context_menu_open_settings);
        findPreference("open_taskbar_settings").setOnPreferenceClickListener(this);
        findPreference("start_menu_apps").setOnPreferenceClickListener(this);

        if (U.launcherIsDefault(this) && FreeformHackHelper.getInstance().isInFreeformWorkspace()) {
            addPreferencesFromResource(R.xml.pref_context_menu_change_wallpaper);
            findPreference("change_wallpaper").setOnPreferenceClickListener(this);
        }//from w  w  w  .  j  av a2s .co  m

        if (!getIntent().getBooleanExtra("dont_show_quit", false)) {
            addPreferencesFromResource(R.xml.pref_context_menu_quit);
            findPreference("quit_taskbar").setOnPreferenceClickListener(this);
        }
    } else if (isOverflowMenu) {
        if (getResources().getConfiguration().screenWidthDp >= 600
                && Build.VERSION.SDK_INT <= Build.VERSION_CODES.M)
            setTitle(R.string.tools);
        else {
            addPreferencesFromResource(R.xml.pref_context_menu_header);
            findPreference("header").setTitle(R.string.tools);
        }

        addPreferencesFromResource(R.xml.pref_context_menu_overflow);
        findPreference("volume").setOnPreferenceClickListener(this);
        findPreference("system_settings").setOnPreferenceClickListener(this);
        findPreference("lock_device").setOnPreferenceClickListener(this);
        findPreference("power_menu").setOnPreferenceClickListener(this);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
            findPreference("file_manager").setOnPreferenceClickListener(this);
        else
            getPreferenceScreen().removePreference(findPreference("file_manager"));
    } else {
        appName = getIntent().getStringExtra("app_name");
        packageName = getIntent().getStringExtra("package_name");
        componentName = getIntent().getStringExtra("component_name");
        userId = getIntent().getLongExtra("user_id", 0);

        if (getResources().getConfiguration().screenWidthDp >= 600
                && Build.VERSION.SDK_INT <= Build.VERSION_CODES.M)
            setTitle(appName);
        else {
            addPreferencesFromResource(R.xml.pref_context_menu_header);
            findPreference("header").setTitle(appName);
        }

        SharedPreferences pref = U.getSharedPreferences(this);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N && pref.getBoolean("freeform_hack", false)
                && !U.isGame(this, packageName)) {
            addPreferencesFromResource(R.xml.pref_context_menu_show_window_sizes);
            findPreference("show_window_sizes").setOnPreferenceClickListener(this);
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N_MR1) {
            int shortcutCount = getLauncherShortcuts();

            if (shortcutCount > 1) {
                addPreferencesFromResource(R.xml.pref_context_menu_shortcuts);
                findPreference("app_shortcuts").setOnPreferenceClickListener(this);
            } else if (shortcutCount == 1)
                generateShortcuts();
        }

        final PackageManager pm = getPackageManager();
        Intent homeIntent = new Intent(Intent.ACTION_MAIN);
        homeIntent.addCategory(Intent.CATEGORY_HOME);
        ResolveInfo defaultLauncher = pm.resolveActivity(homeIntent, PackageManager.MATCH_DEFAULT_ONLY);

        if (!packageName.contains(BuildConfig.BASE_APPLICATION_ID)
                && !packageName.equals(defaultLauncher.activityInfo.packageName)) {
            PinnedBlockedApps pba = PinnedBlockedApps.getInstance(this);

            if (pba.isPinned(componentName)) {
                addPreferencesFromResource(R.xml.pref_context_menu_pin);
                findPreference("pin_app").setOnPreferenceClickListener(this);
                findPreference("pin_app").setTitle(R.string.unpin_app);
            } else if (pba.isBlocked(componentName)) {
                addPreferencesFromResource(R.xml.pref_context_menu_block);
                findPreference("block_app").setOnPreferenceClickListener(this);
                findPreference("block_app").setTitle(R.string.unblock_app);
            } else {
                final int MAX_NUM_OF_COLUMNS = U.getMaxNumOfEntries(this);

                if (pba.getPinnedApps().size() < MAX_NUM_OF_COLUMNS) {
                    addPreferencesFromResource(R.xml.pref_context_menu_pin);
                    findPreference("pin_app").setOnPreferenceClickListener(this);
                    findPreference("pin_app").setTitle(R.string.pin_app);
                }

                addPreferencesFromResource(R.xml.pref_context_menu_block);
                findPreference("block_app").setOnPreferenceClickListener(this);
                findPreference("block_app").setTitle(R.string.block_app);
            }
        }

        addPreferencesFromResource(R.xml.pref_context_menu);

        findPreference("app_info").setOnPreferenceClickListener(this);
        findPreference("uninstall").setOnPreferenceClickListener(this);
    }
}

From source file:android.com.example.contactslist.ui.ContactDetailFragment.java

/**
 * Builds an address LinearLayout based on address information from the Contacts Provider.
 * Each address for the contact gets its own LinearLayout object; for example, if the contact
 * has three postal addresses, then 3 LinearLayouts are generated.
 *
 * @param addressType From/*from  ww w.j  a v  a2 s  .  co m*/
 * {@link StructuredPostal#TYPE}
 * @param addressTypeLabel From
 * {@link StructuredPostal#LABEL}
 * @param address From
 * {@link StructuredPostal#FORMATTED_ADDRESS}
 * @return A LinearLayout to add to the contact details layout,
 *         populated with the provided address details.
 */
private LinearLayout buildAddressLayout(int addressType, String addressTypeLabel, final String address) {

    // Inflates the address layout
    final LinearLayout addressLayout = (LinearLayout) LayoutInflater.from(getActivity())
            .inflate(R.layout.contact_detail_item, mDetailsLayout, false);

    // Gets handles to the view objects in the layout
    final TextView headerTextView = (TextView) addressLayout.findViewById(R.id.contact_detail_header);
    final TextView addressTextView = (TextView) addressLayout.findViewById(R.id.contact_detail_item);
    final ImageButton viewAddressButton = (ImageButton) addressLayout.findViewById(R.id.button_view_address);

    // If there's no addresses for the contact, shows the empty view and message, and hides the
    // header and button.
    if (addressTypeLabel == null && addressType == 0) {
        headerTextView.setVisibility(View.GONE);
        viewAddressButton.setVisibility(View.GONE);
        addressTextView.setText(R.string.no_address);
    } else {
        // Gets postal address label type
        CharSequence label = StructuredPostal.getTypeLabel(getResources(), addressType, addressTypeLabel);

        // Sets TextView objects in the layout
        headerTextView.setText(label);
        addressTextView.setText(address);

        // Defines an onClickListener object for the address button
        viewAddressButton.setOnClickListener(new View.OnClickListener() {
            // Defines what to do when users click the address button
            @Override
            public void onClick(View view) {

                final Intent viewIntent = new Intent(Intent.ACTION_VIEW, constructGeoUri(address));

                // A PackageManager instance is needed to verify that there's a default app
                // that handles ACTION_VIEW and a geo Uri.
                final PackageManager packageManager = getActivity().getPackageManager();

                // Checks for an activity that can handle this intent. Preferred in this
                // case over Intent.createChooser() as it will still let the user choose
                // a default (or use a previously set default) for geo Uris.
                if (packageManager.resolveActivity(viewIntent, PackageManager.MATCH_DEFAULT_ONLY) != null) {
                    startActivity(viewIntent);
                } else {
                    // If no default is found, displays a message that no activity can handle
                    // the view button.
                    Toast.makeText(getActivity(), R.string.no_intent_found, Toast.LENGTH_SHORT).show();
                }
            }
        });

    }
    return addressLayout;
}

From source file:br.com.mybaby.contatos.ContactDetailFragment.java

/**
  * Builds an address LinearLayout based on address information from the Contacts Provider.
  * Each address for the contact gets its own LinearLayout object; for example, if the contact
  * has three postal addresses, then 3 LinearLayouts are generated.
  */*w w w .j a v a2  s .c om*/
  * @param addressType From
  * {@link android.provider.ContactsContract.CommonDataKinds.StructuredPostal#TYPE}
  * @param addressTypeLabel From
  * {@link android.provider.ContactsContract.CommonDataKinds.StructuredPostal#LABEL}
  * @param address From
  * {@link android.provider.ContactsContract.CommonDataKinds.StructuredPostal#FORMATTED_ADDRESS}
  * @return A LinearLayout to add to the contact details layout,
  *         populated with the provided address details.
  */
private LinearLayout buildAddressLayout(int addressType, String addressTypeLabel, final String address) {

    // Inflates the address layout
    final LinearLayout addressLayout = (LinearLayout) LayoutInflater.from(getActivity())
            .inflate(R.layout.contatos_detail_item, mDetailsLayout, false);

    // Gets handles to the view objects in the layout
    final TextView headerTextView = (TextView) addressLayout.findViewById(R.id.contact_detail_header);
    final TextView addressTextView = (TextView) addressLayout.findViewById(R.id.contact_detail_item);
    final ImageButton viewAddressButton = (ImageButton) addressLayout.findViewById(R.id.button_view_address);

    // If there's no addresses for the contact, shows the empty view and message, and hides the
    // header and button.
    if (addressTypeLabel == null && addressType == 0) {
        headerTextView.setVisibility(View.GONE);
        viewAddressButton.setVisibility(View.GONE);
        addressTextView.setText(R.string.no_address);
    } else {
        // Gets postal address label type
        CharSequence label = StructuredPostal.getTypeLabel(getResources(), addressType, addressTypeLabel);

        // Sets TextView objects in the layout
        headerTextView.setText(label);
        addressTextView.setText(address);

        // Defines an onClickListener object for the address button
        viewAddressButton.setOnClickListener(new View.OnClickListener() {
            // Defines what to do when users click the address button
            @Override
            public void onClick(View view) {

                final Intent viewIntent = new Intent(Intent.ACTION_VIEW, constructGeoUri(address));

                // A PackageManager instance is needed to verify that there's a default app
                // that handles ACTION_VIEW and a geo Uri.
                final PackageManager packageManager = getActivity().getPackageManager();

                // Checks for an activity that can handle this intent. Preferred in this
                // case over Intent.createChooser() as it will still let the user choose
                // a default (or use a previously set default) for geo Uris.
                if (packageManager.resolveActivity(viewIntent, PackageManager.MATCH_DEFAULT_ONLY) != null) {
                    startActivity(viewIntent);
                } else {
                    // If no default is found, displays a message that no activity can handle
                    // the view button.
                    Toast.makeText(getActivity(), R.string.no_intent_found, Toast.LENGTH_SHORT).show();
                }
            }
        });

    }
    return addressLayout;
}

From source file:es.example.contacts.ui.ContactDetailFragment.java

/**
 * Builds an address LinearLayout based on address information from the Contacts Provider.
 * Each address for the contact gets its own LinearLayout object; for example, if the contact
 * has three postal addresses, then 3 LinearLayouts are generated.
 *
 * @param addressType From//from w ww.j  a v a 2 s  .  c o m
 * {@link android.provider.ContactsContract.CommonDataKinds.StructuredPostal#TYPE}
 * @param addressTypeLabel From
 * {@link android.provider.ContactsContract.CommonDataKinds.StructuredPostal#LABEL}
 * @param address From
 * {@link android.provider.ContactsContract.CommonDataKinds.StructuredPostal#FORMATTED_ADDRESS}
 * @param phone From
 * {@link android.provider.ContactsContract.CommonDataKinds.Phone#NUMBER}
 * @param data1 From
 * {@link android.provider.ContactsContract.Data#DATA1}
 * @param _id From
 * {@link android.provider.ContactsContract#}
 * @return A LinearLayout to add to the contact details layout,
 *         populated with the provided address details.
 */
private LinearLayout buildAddressLayout(int addressType, String addressTypeLabel, final String address,
        final String phone, final String data1, final String _id, final String _name) {

    // Inflates the address layout
    final LinearLayout addressLayout = (LinearLayout) LayoutInflater.from(getActivity())
            .inflate(R.layout.contact_detail_item, mDetailsLayout, false);

    // Gets handles to the view objects in the layout
    final TextView headerTextView = (TextView) addressLayout.findViewById(R.id.contact_detail_header);
    final TextView addressTextView = (TextView) addressLayout.findViewById(R.id.contact_detail_item);
    final ImageButton viewAddressButton = (ImageButton) addressLayout.findViewById(R.id.button_view_address);
    final TextView phoneTextView = (TextView) addressLayout.findViewById(R.id.contact_phone);
    final SeekBar levelSeekBar = (SeekBar) addressLayout.findViewById(R.id.contact_level);
    final ImageButton saveButton = (ImageButton) addressLayout.findViewById(R.id.button_save);

    Integer prioridad = Integer.parseInt(data1 == null ? "4" : data1);
    // If there's no addresses for the contact, shows the empty view and message, and hides the
    // header and button.
    if (addressTypeLabel == null && addressType == 0 && phone == null) {
        headerTextView.setVisibility(View.GONE);
        viewAddressButton.setVisibility(View.GONE);
        addressTextView.setText(R.string.no_address);
    } else {
        // Gets postal address label type
        CharSequence label = StructuredPostal.getTypeLabel(getResources(), addressType, addressTypeLabel);

        // Sets TextView objects in the layout
        headerTextView.setText(label);
        addressTextView.setText(address);
        phoneTextView.setText(phone);
        levelSeekBar.setProgress(prioridad);

        // Defines an onClickListener object for the address button
        viewAddressButton.setOnClickListener(new View.OnClickListener() {
            // Defines what to do when users click the address button
            @Override
            public void onClick(View view) {

                final Intent viewIntent = new Intent(Intent.ACTION_VIEW, constructGeoUri(address));

                // A PackageManager instance is needed to verify that there's a default app
                // that handles ACTION_VIEW and a geo Uri.
                final PackageManager packageManager = getActivity().getPackageManager();

                // Checks for an activity that can handle this intent. Preferred in this
                // case over Intent.createChooser() as it will still let the user choose
                // a default (or use a previously set default) for geo Uris.
                if (packageManager.resolveActivity(viewIntent, PackageManager.MATCH_DEFAULT_ONLY) != null) {
                    startActivity(viewIntent);
                } else {
                    // If no default is found, displays a message that no activity can handle
                    // the view button.
                    Toast.makeText(getActivity(), R.string.no_intent_found, Toast.LENGTH_SHORT).show();
                }
            }
        });

        // Defines an onClickListener object for the save button
        saveButton.setOnClickListener(new View.OnClickListener() {
            // Defines what to do when users click the address button
            @Override
            public void onClick(View view) {
                // Creates a new intent for sending to the device's contacts application
                // Creates a new array of ContentProviderOperation objects.
                ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();

                Integer prioridad = levelSeekBar.getProgress();
                Log.d("ContactDetalFragment", _id);

                ContentProviderOperation.Builder op;
                if (data1 == null) {
                    Uri uri = addCallerIsSyncAdapterParameter(Data.CONTENT_URI, true);
                    ops.add(ContentProviderOperation.newInsert(ContactsContract.RawContacts.CONTENT_URI)
                            .withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, null)
                            .withValue(ContactsContract.RawContacts.ACCOUNT_NAME, null).build());

                    ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
                            .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
                            .withValue(ContactsContract.Data.MIMETYPE,
                                    ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)
                            .withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, _name)
                            .build());

                    op = ContentProviderOperation.newInsert(Data.CONTENT_URI)
                            .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
                            .withValue(Data.DATA1, prioridad).withValue(Data.MIMETYPE, LEVEL_MIME_TYPE);

                } else {
                    String where = Data.MIMETYPE + " = ? ";
                    String[] params = new String[] { LEVEL_MIME_TYPE, };

                    op = ContentProviderOperation.newUpdate(Data.CONTENT_URI).withSelection(where, params)
                            .withValue(Data.DATA1, prioridad);

                }
                ops.add(op.build());
                try {
                    ContentProviderResult[] results = view.getContext().getContentResolver()
                            .applyBatch(ContactsContract.AUTHORITY, ops);
                } catch (Exception e) {
                    CharSequence txt = getString(R.string.contactUpdateFailure);
                    int duration = Toast.LENGTH_SHORT;
                    Toast toast = Toast.makeText(view.getContext(), txt, duration);
                    toast.show();
                    // Log exception
                    Log.e(TAG, "Exception encountered while inserting contact: " + e);
                }
            }
        });

    }
    return addressLayout;
}

From source file:edu.umbc.cs.ebiquity.mithril.parserapp.contentparsers.contacts.ContactDetailFragment.java

/**
 * Builds a phone number LinearLayout based on phone number info from the Contacts Provider.
 * Each phone number gets its own LinearLayout object; for example, if the contact
 * has three phone numbers, then 3 LinearLayouts are generated.
 *
 * @param addressType From//from ww w .  ja  v a 2s  .  co  m
 * {@link android.provider.ContactsContract.CommonDataKinds.StructuredPostal#TYPE}
 * @param addressTypeLabel From
 * {@link android.provider.ContactsContract.CommonDataKinds.StructuredPostal#LABEL}
 * @param address From
 * {@link android.provider.ContactsContract.CommonDataKinds.StructuredPostal#FORMATTED_ADDRESS}
 * @return A LinearLayout to add to the contact details layout,
 *         populated with the provided phone details.
 */
private LinearLayout buildPhoneLayout(String phoneNumber, int phoneType) {

    // Inflates the phone number layout
    final LinearLayout phoneLayout = (LinearLayout) LayoutInflater.from(getActivity())
            .inflate(R.layout.contact_phone_item, mPhoneLayout, false);

    // Gets handles to the view objects in the layout
    final TextView headerTextView = (TextView) phoneLayout.findViewById(R.id.contact_phone_header);
    final TextView phoneTextView = (TextView) phoneLayout.findViewById(R.id.contact_phone_item);
    final ImageButton dialNumberButton = (ImageButton) phoneLayout.findViewById(R.id.button_call_number);

    // If there's no phone number for the contact, shows the empty view and message, and hides the
    // header and button.
    if (phoneNumber == null && phoneType == 0) {
        headerTextView.setText("");
        dialNumberButton.setVisibility(View.GONE);
        phoneTextView.setText(R.string.no_address);
    } else {
        headerTextView.setText("Phone Number");
        phoneTextView.setText(phoneNumber);

        // add PhoneStateListener
        PhoneCallListener phoneListener = new PhoneCallListener();
        TelephonyManager telephonyManager = (TelephonyManager) getActivity()
                .getSystemService(Context.TELEPHONY_SERVICE);
        telephonyManager.listen(phoneListener, PhoneStateListener.LISTEN_CALL_STATE);

        // Defines an onClickListener object for the call number button
        dialNumberButton.setOnClickListener(new View.OnClickListener() {
            // Defines what to do when users click the address button
            @Override
            public void onClick(View view) {
                Intent dialIntent = null;
                if (!phoneTextView.equals("")) {
                    Uri number = Uri.parse("tel:" + phoneTextView.getText());
                    //                  Log.v(ParserApplication.getDebugTag(), "Calling the number: "+number.toString());
                    dialIntent = new Intent(Intent.ACTION_CALL, number);
                    startActivity(dialIntent);
                }
                // A PackageManager instance is needed to verify that there's a default app
                // that handles ACTION_VIEW and a geo Uri.
                final PackageManager packageManager = getActivity().getPackageManager();

                // Checks for an activity that can handle this intent. Preferred in this
                // case over Intent.createChooser() as it will still let the user choose
                // a default (or use a previously set default) for geo Uris.
                if (packageManager.resolveActivity(dialIntent, PackageManager.MATCH_DEFAULT_ONLY) != null) {
                    startActivity(dialIntent);
                } else {
                    // If no default is found, displays a message that no activity can handle
                    // the view button.
                    Toast.makeText(getActivity(), R.string.no_intent_found, Toast.LENGTH_SHORT).show();
                }
            }
        });

    }
    return phoneLayout;
}

From source file:bolts.AppLinkNavigation.java

/**
 * Performs the navigation.//w  ww  . j  a v  a2 s .  c om
 *
 * @param context the Context from which the navigation should be performed.
 * @return the {@link NavigationResult} performed by navigating.
 */
public NavigationResult navigate(Context context) {
    PackageManager pm = context.getPackageManager();
    Bundle finalAppLinkData = buildAppLinkDataForNavigation(context);

    Intent eligibleTargetIntent = null;
    for (AppLink.Target target : getAppLink().getTargets()) {
        Intent targetIntent = new Intent(Intent.ACTION_VIEW);
        if (target.getUrl() != null) {
            targetIntent.setData(target.getUrl());
        } else {
            targetIntent.setData(appLink.getSourceUrl());
        }
        targetIntent.setPackage(target.getPackageName());
        if (target.getClassName() != null) {
            targetIntent.setClassName(target.getPackageName(), target.getClassName());
        }
        targetIntent.putExtra(AppLinks.KEY_NAME_APPLINK_DATA, finalAppLinkData);

        ResolveInfo resolved = pm.resolveActivity(targetIntent, PackageManager.MATCH_DEFAULT_ONLY);
        if (resolved != null) {
            eligibleTargetIntent = targetIntent;
            break;
        }
    }

    Intent outIntent = null;
    NavigationResult result = NavigationResult.FAILED;
    if (eligibleTargetIntent != null) {
        outIntent = eligibleTargetIntent;
        result = NavigationResult.APP;
    } else {
        // Fall back to the web if it's available
        Uri webUrl = getAppLink().getWebUrl();
        if (webUrl != null) {
            JSONObject appLinkDataJson;
            try {
                appLinkDataJson = getJSONForBundle(finalAppLinkData);
            } catch (JSONException e) {
                sendAppLinkNavigateEventBroadcast(context, eligibleTargetIntent, NavigationResult.FAILED, e);
                throw new RuntimeException(e);
            }
            webUrl = webUrl.buildUpon()
                    .appendQueryParameter(AppLinks.KEY_NAME_APPLINK_DATA, appLinkDataJson.toString()).build();
            outIntent = new Intent(Intent.ACTION_VIEW, webUrl);
            result = NavigationResult.WEB;
        }
    }

    sendAppLinkNavigateEventBroadcast(context, outIntent, result, null);
    if (outIntent != null) {
        context.startActivity(outIntent);
    }
    return result;
}

From source file:com.hivewallet.androidclient.wallet.ui.WalletActivity.java

private Dialog createTimeskewAlertDialog(final long diffMinutes) {
    final PackageManager pm = getPackageManager();
    final Intent settingsIntent = new Intent(android.provider.Settings.ACTION_DATE_SETTINGS);

    final DialogBuilder dialog = DialogBuilder.warn(this, R.string.wallet_timeskew_dialog_title);
    dialog.setMessage(getString(R.string.wallet_timeskew_dialog_msg, diffMinutes));

    if (pm.resolveActivity(settingsIntent, 0) != null) {
        dialog.setPositiveButton(R.string.button_settings, new DialogInterface.OnClickListener() {
            @Override/*from  www .  j  av a2 s .  co  m*/
            public void onClick(final DialogInterface dialog, final int id) {
                startActivity(settingsIntent);
                finish();
            }
        });
    }

    dialog.setNegativeButton(R.string.button_dismiss, null);
    return dialog.create();
}

From source file:com.mobileglobe.android.customdialer.common.model.AccountTypeManager.java

/**
 * Return all usable {@link AccountType}s that support the "invite" feature from the
 * list of all potential invitable account types (retrieved from
 * {@link #getAllInvitableAccountTypes}). A usable invitable account type means:
 * (1) there is at least 1 raw contact in the database with that account type, and
 * (2) the app contributing the account type is not disabled.
 *
 * Warning: Don't use on the UI thread because this can scan the database.
 *//*www  .  ja va2s .c  om*/
private Map<AccountTypeWithDataSet, AccountType> findUsableInvitableAccountTypes(Context context) {
    Map<AccountTypeWithDataSet, AccountType> allInvitables = getAllInvitableAccountTypes();
    if (allInvitables.isEmpty()) {
        return EMPTY_UNMODIFIABLE_ACCOUNT_TYPE_MAP;
    }

    final HashMap<AccountTypeWithDataSet, AccountType> result = Maps.newHashMap();
    result.putAll(allInvitables);

    final PackageManager packageManager = context.getPackageManager();
    for (AccountTypeWithDataSet accountTypeWithDataSet : allInvitables.keySet()) {
        AccountType accountType = allInvitables.get(accountTypeWithDataSet);

        // Make sure that account types don't come from apps that are disabled.
        Intent invitableIntent = MoreContactUtils.getInvitableIntent(accountType, SAMPLE_CONTACT_URI);
        if (invitableIntent == null) {
            result.remove(accountTypeWithDataSet);
            continue;
        }
        ResolveInfo resolveInfo = packageManager.resolveActivity(invitableIntent,
                PackageManager.MATCH_DEFAULT_ONLY);
        if (resolveInfo == null) {
            // If we can't find an activity to start for this intent, then there's no point in
            // showing this option to the user.
            result.remove(accountTypeWithDataSet);
            continue;
        }

        // Make sure that there is at least 1 raw contact with this account type. This check
        // is non-trivial and should not be done on the UI thread.
        if (!accountTypeWithDataSet.hasData(context)) {
            result.remove(accountTypeWithDataSet);
        }
    }

    return Collections.unmodifiableMap(result);
}