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:org.alfresco.mobile.android.application.fragments.user.UserProfileFragment.java

/**
 * Install the Skype client through the market: URI scheme.
 *//*from w w  w  .ja  v a2s . c o m*/
public void goToMarket(Context myContext) {
    try {
        Uri marketUri = Uri.parse("market://details?type=com.skype.raider");
        Intent myIntent = new Intent(Intent.ACTION_VIEW, marketUri);
        myIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (myIntent.resolveActivity(myContext.getPackageManager()) == null) {
            AlfrescoNotificationManager.getInstance(myContext).showAlertCrouton((FragmentActivity) myContext,
                    myContext.getString(R.string.feature_disable));
            return;
        }
        myContext.startActivity(myIntent);
    } catch (ActivityNotFoundException e) {

    }
}

From source file:net.gsantner.opoc.util.ShareUtil.java

/**
 * Request a picture from camera-like apps
 * Result ({@link String}) will be available from {@link Activity#onActivityResult(int, int, Intent)}.
 * It has set resultCode to {@link Activity#RESULT_OK} with same requestCode, if successfully
 * The requested image savepath has to be stored at caller side (not contained in intent),
 * it can be retrieved using {@link #extractResultFromActivityResult(int, int, Intent)},
 * returns null if an error happened./*  w  w w  .  j  a  v  a2s . c om*/
 *
 * @param target Path to file to write to, if folder the filename gets app_name + millis + random filename. If null DCIM folder is used.
 */
public String requestCameraPicture(File target) {
    if (!(_context instanceof Activity)) {
        throw new RuntimeException("Error: ShareUtil.requestCameraPicture needs an Activity Context.");
    }
    String cameraPictureFilepath = null;
    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    if (takePictureIntent.resolveActivity(_context.getPackageManager()) != null) {
        File photoFile;
        try {
            // Create an image file name
            if (target != null && !target.isDirectory()) {
                photoFile = target;
            } else {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH-mm-ss", Locale.getDefault());
                File storageDir = target != null ? target
                        : new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM),
                                "Camera");
                String imageFileName = ((new ContextUtils(_context).rstr("app_name"))
                        .replaceAll("[^a-zA-Z0-9\\.\\-]", "_") + "_").replace("__", "_")
                        + sdf.format(new Date());
                photoFile = new File(storageDir, imageFileName + ".jpg");
                if (!photoFile.getParentFile().exists() && !photoFile.getParentFile().mkdirs()) {
                    photoFile = File.createTempFile(imageFileName + "_", ".jpg", storageDir);
                }
            }

            //noinspection StatementWithEmptyBody
            if (!photoFile.getParentFile().exists() && photoFile.getParentFile().mkdirs())
                ;

            // Save a file: path for use with ACTION_VIEW intents
            cameraPictureFilepath = photoFile.getAbsolutePath();
        } catch (IOException ex) {
            return null;
        }

        // Continue only if the File was successfully created
        if (photoFile != null) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                Uri uri = FileProvider.getUriForFile(_context, getFileProviderAuthority(), photoFile);
                takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
            } else {
                takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
            }
            ((Activity) _context).startActivityForResult(takePictureIntent, REQUEST_CAMERA_PICTURE);
        }
    }
    _lastCameraPictureFilepath = cameraPictureFilepath;
    return cameraPictureFilepath;
}

From source file:no.nordicsemi.android.nrftoolbox.dfu.DfuActivity.java

/**
 * Called when Select File was pressed//from   w  w  w .  ja va  2  s.com
 * 
 * @param view
 *            a button that was pressed
 */
public void onSelectFileClicked(final View view) {
    final Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
    intent.setType("application/octet-stream");
    intent.addCategory(Intent.CATEGORY_OPENABLE);
    if (intent.resolveActivity(getPackageManager()) != null) {
        // file browser has been found on the device
        startActivityForResult(intent, SELECT_FILE_REQ);
    } else {
        // there is no any file browser app, let's try to download one
        final View customView = getLayoutInflater().inflate(R.layout.app_file_browser, null);
        final ListView appsList = (ListView) customView.findViewById(android.R.id.list);
        appsList.setAdapter(new FileBrowserAppsAdapter(this));
        appsList.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
        appsList.setItemChecked(0, true);
        new AlertDialog.Builder(this).setTitle(R.string.dfu_alert_no_filebrowser_title).setView(customView)
                .setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(final DialogInterface dialog, final int which) {
                        dialog.dismiss();
                    }
                }).setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(final DialogInterface dialog, final int which) {
                        final int pos = appsList.getCheckedItemPosition();
                        if (pos >= 0) {
                            final String query = getResources()
                                    .getStringArray(R.array.dfu_app_file_browser_action)[pos];
                            final Intent storeIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(query));
                            startActivity(storeIntent);
                        }
                    }
                }).show();
    }
}

From source file:com.amazonaws.mobileconnectors.pinpoint.targeting.notification.NotificationClient.java

private void openURL(final String url, final boolean noSchemeValidation) {
    final String validatedUrl;
    if (url.startsWith("http://") || url.startsWith("https://") || noSchemeValidation) {
        validatedUrl = url;/*from  w  ww. j  a va2 s.  co  m*/
    } else {
        validatedUrl = "http://" + url;
    }

    final Intent intent = new Intent(Intent.ACTION_VIEW);
    intent.setData(Uri.parse(validatedUrl));
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    if (intent.resolveActivity(pinpointContext.getApplicationContext().getPackageManager()) != null) {
        pinpointContext.getApplicationContext().startActivity(intent);
    }
}

From source file:com.dvn.vindecoder.ui.user.GetAllVehicalDetails.java

private void openCameraApplication() {
    Intent picIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    if (picIntent.resolveActivity(getPackageManager()) != null) {
        startActivityForResult(picIntent, CAMERA_REQUEST);
    }//from   w w w  .ja v a2  s . c om
}

From source file:com.ereinecke.eatsafe.MainActivity.java

private void launchPhotoIntent(int whichPhoto) {

    Logd(LOG_TAG, "Launching intent for photo #" + whichPhoto);
    // create Intent to take a picture and return control to the calling application
    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    // Ensure that there's a camera activity to handle the intent
    if (takePictureIntent.resolveActivity(getPackageManager()) != null) {

        // Create the File where the photo should go
        File photoFile = openOutputMediaFile();
        Logd(LOG_TAG, "photoReceived: " + photoReceived);

        if (photoFile != null) {

            Uri photoUri = StreamProvider.getUriForFile("com.ereinecke.eatsafe.fileprovider", photoFile);
            try {
                Logd(LOG_TAG, "photoUri: " + photoUri.toString());
            } catch (Exception e) {
                Logd(LOG_TAG, "photoUri is null: " + e.getMessage());
            }//www  .  j  a  va2 s  .c  o  m
            // set the image file name
            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
            takePictureIntent.putExtra(Constants.WHICH_PHOTO, whichPhoto);
            takePictureIntent
                    .setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);

            // start the image capture Intent
            startActivityForResult(takePictureIntent, Constants.CAMERA_IMAGE_REQUEST);
        }
    }
}

From source file:com.ivanmagda.inventory.ui.ProductEditor.java

/**
 * Helper method for placing an order with the specified supplier.
 *//*w  w w.j a va  2 s . c om*/
private void placeOrder() {
    assert mProduct != null;

    if (mProduct.getReceiveQuantity() == 0) {
        Toast.makeText(this, R.string.place_order_failed_msg, Toast.LENGTH_LONG).show();
        return;
    }

    Intent intent = new Intent(Intent.ACTION_SENDTO);
    intent.setData(Uri.parse("mailto:"));
    intent.putExtra(Intent.EXTRA_EMAIL, new String[] { mProduct.getSupplier() });
    intent.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.place_order_subject) + mProduct.getName());
    intent.putExtra(Intent.EXTRA_TEXT, generateOrderSummary());

    if (intent.resolveActivity(getPackageManager()) != null) {
        startActivity(intent);
    } else {
        Toast.makeText(this, R.string.send_email_failed_msg, Toast.LENGTH_LONG).show();
    }
}

From source file:com.company.millenium.iwannask.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    //GPS//w ww  . j av  a  2  s  .co  m
    locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
    locationListener = new LocationListener() {
        public void onLocationChanged(Location location) {
            if (ActivityCompat.checkSelfPermission(MainActivity.this,
                    Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                // Check Permissions Now
                final int REQUEST_LOCATION = 2;

                if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this,
                        Manifest.permission.ACCESS_FINE_LOCATION)) {
                    // Display UI and wait for user interaction
                } else {
                    ActivityCompat.requestPermissions(MainActivity.this,
                            new String[] { Manifest.permission.ACCESS_FINE_LOCATION }, REQUEST_LOCATION);
                }
            } else {
                locationManager.removeUpdates(this);
            }
        }

        public void onStatusChanged(String string, int integer, Bundle bundle) {

        }

        public void onProviderEnabled(String string) {

        }

        public void onProviderDisabled(String string) {

        }
    };

    if (ActivityCompat.checkSelfPermission(this,
            Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        // Check Permissions Now
        final int REQUEST_LOCATION = 2;

        if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                Manifest.permission.ACCESS_FINE_LOCATION)) {
            // Display UI and wait for user interaction
        } else {
            ActivityCompat.requestPermissions(this, new String[] { Manifest.permission.ACCESS_FINE_LOCATION },
                    REQUEST_LOCATION);
        }
    } else {
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 1000, locationListener);
    }

    int delay = 30000; // delay for 30 sec.
    int period = 3000000; // repeat every 5.3min.
    Timer timer = new Timer();
    timer.scheduleAtFixedRate(new TimerTask() {
        public void run() {
            if (ActivityCompat.checkSelfPermission(MainActivity.this,
                    Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                // Check Permissions Now
                final int REQUEST_LOCATION = 2;

                if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this,
                        Manifest.permission.ACCESS_FINE_LOCATION)) {
                    // Display UI and wait for user interaction
                } else {
                    ActivityCompat.requestPermissions(MainActivity.this,
                            new String[] { Manifest.permission.ACCESS_FINE_LOCATION }, REQUEST_LOCATION);
                }
            } else {
                locationManager.removeUpdates(locationListener);
            }
        }
    }, delay, period);

    getWindow().addFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);

    Intent mIntent = getIntent();
    URL = Constants.SERVER_URL;
    if (mIntent.hasExtra("url")) {
        myWebView = null;
        startActivity(getIntent());
        String url = mIntent.getStringExtra("url");
        URL = Constants.SERVER_URL + url;
    }

    CookieSyncManager.createInstance(this);
    CookieSyncManager.getInstance().startSync();
    myWebView = (WebView) findViewById(R.id.webview);
    myWebView.getSettings().setGeolocationDatabasePath(this.getFilesDir().getPath());
    myWebView.getSettings().setGeolocationEnabled(true);
    WebSettings webSettings = myWebView.getSettings();
    webSettings.setUseWideViewPort(false);
    if (!DetectConnection.checkInternetConnection(this)) {
        webSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
        showNoConnectionDialog(this);
    } else {
        webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);
    }
    webSettings.setJavaScriptEnabled(true);
    myWebView.addJavascriptInterface(new webappinterface(this), "android");
    webSettings.setLoadWithOverviewMode(true);
    webSettings.setUseWideViewPort(true);
    myWebView.setOverScrollMode(View.OVER_SCROLL_NEVER);

    //location test
    webSettings.setAppCacheEnabled(true);
    webSettings.setDatabaseEnabled(true);
    webSettings.setDomStorageEnabled(true);

    myWebView.setWebViewClient(new WebViewClient() {
        @Override
        public void onPageFinished(WebView view, String url) {
            CookieSyncManager.getInstance().sync();
        }

        @Override
        public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
            handler.proceed(); // Ignore SSL certificate errors
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if (Uri.parse(url).getHost().equals(Constants.HOST)
                    || Uri.parse(url).getHost().equals(Constants.WWWHOST)) {
                // This is my web site, so do not override; let my WebView load
                // the page
                return false;
            }
            // Otherwise, the link is not for a page on my site, so launch
            // another Activity that handles URLs
            Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
            startActivity(intent);
            return true;
        }
    });
    myWebView.setWebChromeClient(new WebChromeClient() {
        public void onGeolocationPermissionsShowPrompt(String origin,
                GeolocationPermissions.Callback callback) {
            callback.invoke(origin, true, false);
        }

        @Override
        public void onPermissionRequest(final PermissionRequest request) {
            Log.d(TAG, "onPermissionRequest");
            runOnUiThread(new Runnable() {
                @TargetApi(Build.VERSION_CODES.LOLLIPOP)
                @Override
                public void run() {
                    if (request.getOrigin().toString().equals("https://apprtc-m.appspot.com/")) {
                        request.grant(request.getResources());
                    } else {
                        request.deny();
                    }
                }
            });
        }

        public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback,
                WebChromeClient.FileChooserParams fileChooserParams) {

            // Double check that we don't have any existing callbacks
            if (mFilePathCallback != null) {
                mFilePathCallback.onReceiveValue(null);
            }
            mFilePathCallback = filePathCallback;

            // Set up the take picture intent
            Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
                // Create the File where the photo should go
                File photoFile = null;
                try {
                    photoFile = createImageFile();
                    takePictureIntent.putExtra("PhotoPath", mCameraPhotoPath);
                } catch (IOException ex) {
                    // Error occurred while creating the File
                    Log.e(TAG, "Unable to create Image File", ex);
                }

                // Continue only if the File was successfully created
                if (photoFile != null) {
                    mCameraPhotoPath = "file:" + photoFile.getAbsolutePath();
                    takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
                } else {
                    takePictureIntent = null;
                }
            }

            // Set up the intent to get an existing image
            Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT);
            contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);
            contentSelectionIntent.setType("image/*");

            // Set up the intents for the Intent chooser
            Intent[] intentArray;
            if (takePictureIntent != null) {
                intentArray = new Intent[] { takePictureIntent };
            } else {
                intentArray = new Intent[0];
            }

            Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);
            chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent);
            chooserIntent.putExtra(Intent.EXTRA_TITLE, "Image Chooser");
            chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray);

            startActivityForResult(chooserIntent, INPUT_FILE_REQUEST_CODE);

            return true;
        }

    });
    // setContentView(myWebView);
    //        myWebView.loadUrl(URL);
    myWebView.loadUrl(URL);
    mRegistrationBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            //                mRegistrationProgressBar.setVisibility(ProgressBar.GONE);
            SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
            boolean sentToken = sharedPreferences.getBoolean(QuickstartPreferences.SENT_TOKEN_TO_SERVER, false);
        }
    };

    //CookieManager mCookieManager = CookieManager.getInstance();
    //Boolean hasCookies = mCookieManager.hasCookies();
    //while(!hasCookies);

    if (checkPlayServices()) {
        // Start IntentService to register this application with GCM.
        Intent intent = new Intent(this, RegistrationIntentService.class);
        //intent.putExtra("session", session);
        startService(intent);
    }

    Boolean isFirstRun = getSharedPreferences("PREFERENCE", MODE_PRIVATE).getBoolean("isFirstRun", true);

    if (isFirstRun) {
        //show start activity
        startActivity(new Intent(MainActivity.this, MyIntro.class));
    }
    //if (!isOnline())
    //    showNoConnectionDialog(this);
    getSharedPreferences("PREFERENCE", MODE_PRIVATE).edit().putBoolean("isFirstRun", false).commit();

    //Pull-to-refresh
    mSwipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.container);
    mSwipeRefreshLayout.setOnRefreshListener(this);
}

From source file:com.salmannazir.filemanager.businesslogic.EventHandler.java

private void showNewImageCreateDialog(final Activity mContext, final String directory) {
    boolean wrapInScrollView = true;

    new MaterialDialog.Builder(mContext).title("Create New Image File")
            .customView(R.layout.new_image_layout, wrapInScrollView).positiveText("Capture Image")
            .negativeText("Cancel").onPositive(new MaterialDialog.SingleButtonCallback() {
                @Override/*from   ww w  .j a  v  a  2 s. co m*/
                public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                    // TODO
                    Toast.makeText(mContext, "+ve Clicked", Toast.LENGTH_SHORT).show();
                    Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    if (cameraIntent.resolveActivity(mContext.getPackageManager()) != null) {
                        // Create the File where the photo should go
                        File photoFile = null;
                        try {
                            EditText imageNameEditText = (EditText) dialog.findViewById(R.id.image_name);
                            photoFile = createImageFile(imageNameEditText.getText().toString(), directory);
                        } catch (IOException ex) {
                            // Error occurred while creating the File
                            Log.i("MainActivity", "IOException");
                        }
                        // Continue only if the File was successfully created
                        if (photoFile != null) {
                            cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
                            mContext.startActivityForResult(cameraIntent, Constants.CAMERA_REQUEST);
                        }
                    }
                }
            }).show();
}

From source file:com.example.volunteerhandbook.MainActivity.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    if (noDrawYet)
        return true;
    // The action bar home/up action should open or close the drawer.
    // ActionBarDrawerToggle will take care of this.
    if (mDrawerToggle.onOptionsItemSelected(item)) {
        return true;
    }/*w  w w. j  av  a 2 s.c om*/
    // Handle action buttons
    closeSpeaker();
    ListRecordBase record = (ListRecordBase) mCurrentFragment;
    int itemId = item.getItemId();
    switch (itemId) {
    case R.id.action_new:
    case R.id.action_modify:
    case R.id.action_delete:
    case R.id.action_check:
    case R.id.action_save:
        record.getArguments().putInt(ListRecordBase.ACTION_TYPE, itemId);
        FragmentManager fragmentManager = getFragmentManager();
        fragmentManager.beginTransaction().replace(R.id.main_content_frame, mCurrentFragment).commit();
        break;
    case R.id.action_join:
        break;
    case R.id.action_websearch:
        // create intent to perform web search for this planet
        Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
        intent.putExtra(SearchManager.QUERY, getActionBar().getTitle());
        // catch event that there's no activity to handle intent
        if (intent.resolveActivity(getPackageManager()) != null)
            startActivity(intent);
        else
            Toast.makeText(this, R.string.app_not_available, Toast.LENGTH_LONG).show();
    default:
        super.onOptionsItemSelected(item);
    }
    return true;
}