Example usage for android.content Intent setDataAndType

List of usage examples for android.content Intent setDataAndType

Introduction

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

Prototype

public @NonNull Intent setDataAndType(@Nullable Uri data, @Nullable String type) 

Source Link

Document

(Usually optional) Set the data for the intent along with an explicit MIME data type.

Usage

From source file:br.com.GUI.perfil.PerfilAluno.java

private void cortar(int requestCode) {
    //take care of exceptions
    try {//from   w w  w.  ja v  a2 s .c  om
        //call the standard crop action intent (the user device may not support it)
        Intent cropIntent = new Intent("com.android.camera.action.CROP");
        //indicate image type and Uri
        cropIntent.setDataAndType(selectedImageUri, "image/*");
        //set crop properties
        cropIntent.putExtra("crop", "true");
        //indicate aspect of desired crop
        cropIntent.putExtra("aspectX", 1);
        cropIntent.putExtra("aspectY", 1);
        //indicate output X and Y
        cropIntent.putExtra("outputX", 144);
        cropIntent.putExtra("outputY", 144);
        //retrieve data on return
        cropIntent.putExtra("return-data", true);
        //start the activity - we handle returning in onActivityResult
        startActivityForResult(cropIntent, requestCode + 2);
    }
    //respond to users whose devices do not support the crop action
    catch (ActivityNotFoundException anfe) {
        //display an error message
        String errorMessage = "Whoops - your device doesn't support the crop action!";
        Toast toast = Toast.makeText(getActivity(), errorMessage, Toast.LENGTH_SHORT);
        toast.show();
    }
}

From source file:com.bf.zxd.zhuangxudai.my.fragment.FinancialApplyFragment.java

private void startPhoneZoom(Uri uri) {
    Intent intent = new Intent("com.android.camera.action.CROP");
    intent.setDataAndType(uri, "image/*");
    //???/*w  ww . java  2  s  .  co  m*/
    intent.putExtra("corp", "true");
    //?
    intent.putExtra("aspectY", 1);
    intent.putExtra("aspectX", 1);
    //?
    intent.putExtra("outputX", 150);
    intent.putExtra("outputY", 150);
    //?
    intent.putExtra("return-data", true);
    startActivityForResult(intent, RESULT_PHOTO);
}

From source file:com.gmail.nagamatu.radiko.installer.RadikoInstallerActivity.java

private void download(String urlstr, String marketDa) {
    try {/*from  w  ww  . ja  va2  s  .  c om*/
        final HttpGet request = new HttpGet(urlstr);
        request.addHeader("User-Agent", "Android-Market/2");
        request.addHeader("Cookie", "MarketDA=" + marketDa);

        final HttpResponse response = mClient.execute(request);
        if (response.getStatusLine().getStatusCode() != 200) {
            updateMessage(R.string.error_download, response.getStatusLine().getReasonPhrase());
            return;
        }

        final File file = new File(Environment.getExternalStorageDirectory(), PACKAGE_NAME + ".apk");
        if (file.exists()) {
            file.delete();
        }
        final FileOutputStream out = new FileOutputStream(file);
        final InputStream in = response.getEntity().getContent();
        long total = response.getEntity().getContentLength();
        long len = total;
        try {
            final byte[] buf = new byte[BUFSIZE];
            while (len > 0) {
                int rsz = in.read(buf);
                if (rsz < 0) {
                    break;
                }
                out.write(buf, 0, rsz);
                len -= rsz;
                updateProgress((int) (100 * (total - len) / total));
            }
            if (len != 0) {
                updateMessage(R.string.error_download, "Insufficient Response");
                return;
            }

            updateMessage(R.string.install_package, null);
            final Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
            startActivity(intent);
            finish();
        } finally {
            in.close();
            out.flush();
            out.close();
        }
    } catch (Exception e) {
        updateMessage(R.string.error_download, e.toString());
    }
}

From source file:cn.com.caronwer.activity.CertificationActivity.java

@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
    switch (requestCode) {
    case 100: {//  w w  w.  ja  v  a2  s  . c o  m
        if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            Intent takeIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            //????
            takeIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri
                    .fromFile(new File(Environment.getExternalStorageDirectory(), IMAGE_FILE_NAME[imgType])));
            startActivityForResult(takeIntent, REQUESTCODE_TAKE);
        } else {
            Toast.makeText(CertificationActivity.this, "Permission Denied", Toast.LENGTH_SHORT).show();
        }
        return;
    }
    case 200: {

        if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            Intent pickIntent = new Intent(Intent.ACTION_PICK, null);
            pickIntent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
            startActivityForResult(pickIntent, REQUESTCODE_PICK);
        } else {
            Toast.makeText(CertificationActivity.this, "Permission Denied", Toast.LENGTH_SHORT).show();
        }
        return;
    }
    case 300: {

        if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            //getServletData();
        } else {
            Toast.makeText(CertificationActivity.this, "Permission Denied", Toast.LENGTH_SHORT).show();
        }
        return;
    }
    }
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}

From source file:com.hangulo.powercontact.ErrorContactsListFragment.java

@Override
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {

    PowerContactAddress item = mErrorContactList.get(position); // ? ? ?  -->  .
    mPosition = position; //  ?? ?

    mLastDataId = item.getData_id();//from   ww w  . ja v a 2  s  . c  o  m
    mLastContactId = item.getContact_id();
    mLastLookupKey = item.getLookup_key();
    Uri mSelectedContactUri = ContactsContract.Contacts.getLookupUri(mLastContactId, mLastLookupKey);
    // Creates a new Intent to edit a contact
    Intent editIntent = new Intent(Intent.ACTION_EDIT);
    /*
     * Sets the contact URI to edit, and the data type that the
     * Intent must match
     */
    editIntent.setDataAndType(mSelectedContactUri, ContactsContract.Contacts.CONTENT_ITEM_TYPE);
    // Sets the special extended data for navigation
    editIntent.putExtra("finishActivityOnSaveCompleted", true);
    // Sends the Intent
    getActivity().startActivityForResult(editIntent, Constants.RESULT_ERROR_CONTACTSLIST);

}

From source file:com.alibaba.weex.update.UpdateService.java

private void handleActionUpdate(String url) {
    manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    builder = new NotificationCompat.Builder(this);
    builder.setContentTitle(CheckForUpdateUtil.getStringRes(R.string.update_downloading))
            .setContentText(CheckForUpdateUtil.getStringRes(R.string.update_progress) + " 0%")
            .setTicker(CheckForUpdateUtil.getStringRes(R.string.update_downloading))
            .setWhen(System.currentTimeMillis()).setPriority(Notification.PRIORITY_DEFAULT)
            .setSmallIcon(R.mipmap.ic_launcher).setProgress(100, 0, false);
    manager.notify(NOTIFY_ID, builder.build());

    WXLogUtils.e("Update", "start download");
    Downloader.download(url,/*from   w  w  w.  ja  va 2  s.  c o m*/
            new Downloader.DownloadCallback(getCacheDir().getAbsolutePath(), "playground.apk") {

                @Override
                public void onProgress(float progress) {
                    if (progress * 100 - progress >= 1) {
                        int p = (int) (progress * 100);
                        builder.setContentText(
                                CheckForUpdateUtil.getStringRes(R.string.update_progress) + p + "%");
                        builder.setProgress(100, p, false);
                        manager.notify(NOTIFY_ID, builder.build());
                        WXLogUtils.d("Update", "progress:" + p);
                    }
                }

                @Override
                public void onResponse(File file) {
                    WXLogUtils.d("Update", "success: " + file.getAbsolutePath());
                    manager.cancel(NOTIFY_ID);
                    Uri uri = Uri.fromFile(file);
                    Intent installIntent = new Intent(Intent.ACTION_VIEW);

                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                        installIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                        Uri contentUri = FileProvider.getUriForFile(WXEnvironment.getApplication(),
                                BuildConfig.APPLICATION_ID + ".fileprovider", file);
                        installIntent.setDataAndType(contentUri, "application/vnd.android.package-archive");
                    } else {
                        installIntent.setDataAndType(uri, "application/vnd.android.package-archive");
                        installIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    }
                    startActivity(installIntent);
                }

                @Override
                public void onError(final Exception e) {
                    WXSDKManager.getInstance().getWXRenderManager().postOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(UpdateService.this, "Failed to update:" + e.getMessage(),
                                    Toast.LENGTH_SHORT).show();
                        }
                    }, 0);
                }
            });
}

From source file:com.phonegap.plugins.openfilewithexternalapp.OpenFileWithExternalApp.java

public PluginResult execute(String action, JSONArray args, String callbackId) {

    try {/* www. ja  va2  s. co  m*/

        String filePath = args.getString(0);

        Intent intent = new Intent();

        intent.setAction(android.content.Intent.ACTION_VIEW);

        File fileToOpen = new File(filePath);

        MimeTypeMap mime = MimeTypeMap.getSingleton();

        String extension = fileToOpen.getName().substring(fileToOpen.getName().lastIndexOf(".") + 1)
                .toLowerCase();

        String type = mime.getMimeTypeFromExtension(extension);

        intent.setAction(Intent.ACTION_VIEW);

        Uri uri = Uri.fromFile(fileToOpen);

        intent.setDataAndType(uri, type);

        this.ctx.startActivity(intent);
    }

    catch (JSONException e) {

        e.printStackTrace();

    }

    PluginResult mPlugin = new PluginResult(PluginResult.Status.NO_RESULT);

    return mPlugin;
}

From source file:chinanurse.cn.nurse.Fragment_Nurse_job.IdentityFragment_ACTIVITY.java

/**
 * ?/*from   w  w w. j  a v a 2  s  . com*/
 *
 * @param uri
 */
public void startPhotoZoom(Uri uri) {
    Intent intent = new Intent("com.android.camera.action.CROP");
    intent.setDataAndType(uri, "image/*");
    // ?
    intent.putExtra("crop", "true");
    // aspectX aspectY 
    intent.putExtra("aspectX", 1);
    intent.putExtra("aspectY", 1);
    // outputX outputY ?
    intent.putExtra("outputX", 340);
    intent.putExtra("outputY", 340);
    intent.putExtra("return-data", true);
    startActivityForResult(intent, PHOTO_REQUEST_CUT);
}

From source file:com.dycode.jepretstory.mediachooser.fragment.ImageFragment.java

private void setAdapter(Cursor imagecursor) {

    if (imagecursor.getCount() > 0) {

        mGalleryModelList = new ArrayList<MediaModel>();

        for (int i = 0; i < imagecursor.getCount(); i++) {
            imagecursor.moveToPosition(i);
            int dataColumnIndex = imagecursor.getColumnIndex(MediaStore.Images.Media.DATA);
            //int thumbnailColumnIndex    = imagecursor.getColumnIndex(MediaStore.Images.Thumbnails.DATA);
            int idColumnIndex = imagecursor.getColumnIndex(MediaStore.Images.Media._ID);
            //int idColumnIndex          = imagecursor.getColumnIndex(MediaStore.Images.Thumbnails.IMAGE_ID);
            int bucketColumnIndex = imagecursor.getColumnIndex(MediaStore.Images.Media.BUCKET_ID);
            int orientColumnIndex = imagecursor.getColumnIndex(MediaStore.Images.ImageColumns.ORIENTATION);

            String imgUrl = imagecursor.getString(dataColumnIndex).toString();
            //            boolean selected = false;
            //            if (mSelectedModels != null && mSelectedModels.size() > 0) {
            //               for(String currImgUrl: mSelectedItems) {
            //                  if (currImgUrl.equalsIgnoreCase(imgUrl)) {
            //                     selected = true;
            //                     break;
            //                  }
            //               }
            //            }

            String id = imagecursor.getString(idColumnIndex);
            String thumbId = "";//imagecursor.getString(idColumnIndex);
            String bucketId = imagecursor.getString(bucketColumnIndex);
            String thumbUrl = "";//imagecursor.getString(thumbnailColumnIndex).toString();
            int orientation = imagecursor.getInt(orientColumnIndex);

            MediaModel galleryModel = new MediaModel(bucketId, id, imgUrl, thumbId, thumbUrl, false,
                    MediaType.IMAGE);//  www .  j  av a  2 s  .  c  om
            if (mSelectedModels != null && mSelectedModels.size() > 0) {
                galleryModel.status = mSelectedModels.contains(galleryModel);
            }
            galleryModel.orientation = orientation;

            //processThumbnailImage(id, galleryModel, getActivity());

            mGalleryModelList.add(galleryModel);
        }

        mImageAdapter = new GridViewAdapter(getActivity(), 0, mGalleryModelList, false);
        mImageGridView.setAdapter(mImageAdapter);
    } else {
        Toast.makeText(getActivity(), getActivity().getString(R.string.no_media_file_available),
                Toast.LENGTH_SHORT).show();
    }

    mImageGridView.setOnItemLongClickListener(new OnItemLongClickListener() {

        @Override
        public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {

            GridViewAdapter adapter = (GridViewAdapter) parent.getAdapter();
            MediaModel galleryModel = (MediaModel) adapter.getItem(position);
            File file = new File(galleryModel.url);
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setDataAndType(Uri.fromFile(file), "image/*");
            startActivity(intent);
            return true;
        }
    });

    mImageGridView.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            // update the mStatus of each category in the adapter
            GridViewAdapter adapter = (GridViewAdapter) parent.getAdapter();
            MediaModel galleryModel = (MediaModel) adapter.getItem(position);

            if (!galleryModel.status) {
                long size = MediaChooserConstants.ChekcMediaFileSize(new File(galleryModel.url.toString()),
                        false);
                if (size != 0) {
                    Toast.makeText(getActivity(),
                            getActivity().getResources().getString(R.string.file_size_exeeded) + "  "
                                    + MediaChooserConstants.SELECTED_IMAGE_SIZE_IN_MB + " "
                                    + getActivity().getResources().getString(R.string.mb),
                            Toast.LENGTH_SHORT).show();
                    return;
                }

                if (MediaChooserConstants.MAX_MEDIA_LIMIT == 1) {
                    //remove all first
                    if (mSelectedModels.size() >= 1) {

                        MediaModel selModel = (MediaModel) mSelectedModels.get(0);
                        selModel.status = false;

                        mSelectedModels.clear();
                        MediaChooserConstants.SELECTED_MEDIA_COUNT--;
                    }
                }

                if ((MediaChooserConstants.MAX_MEDIA_LIMIT == MediaChooserConstants.SELECTED_MEDIA_COUNT)) {
                    if (MediaChooserConstants.SELECTED_MEDIA_COUNT < 2) {
                        Toast.makeText(getActivity(),
                                getActivity().getResources().getString(R.string.max_limit_file) + "  "
                                        + MediaChooserConstants.SELECTED_MEDIA_COUNT + " "
                                        + getActivity().getResources().getString(R.string.file),
                                Toast.LENGTH_SHORT).show();
                        return;
                    } else {
                        Toast.makeText(getActivity(),
                                getActivity().getResources().getString(R.string.max_limit_file) + "  "
                                        + MediaChooserConstants.SELECTED_MEDIA_COUNT + " "
                                        + getActivity().getResources().getString(R.string.files),
                                Toast.LENGTH_SHORT).show();
                        return;
                    }

                }
            }

            // inverse the status
            galleryModel.status = !galleryModel.status;

            adapter.notifyDataSetChanged();

            if (galleryModel.status) {
                //mSelectedItems.add(galleryModel.url.toString());
                mSelectedModels.add(galleryModel);
                MediaChooserConstants.SELECTED_MEDIA_COUNT++;

            } else {
                //mSelectedItems.remove(galleryModel.url.toString().trim());
                mSelectedModels.remove(galleryModel);
                MediaChooserConstants.SELECTED_MEDIA_COUNT--;
            }

            if (mCallback != null) {

                mCallback.onImageSelectedCount(mSelectedModels.size());

                if (galleryModel.status) {
                    mCallback.onImageSelected(galleryModel);
                } else {
                    mCallback.onImageUnselected(galleryModel);
                }

                Intent intent = new Intent();
                //intent.putStringArrayListExtra("list", mSelectedItems);
                intent.putParcelableArrayListExtra("selectedImages", mSelectedModels);
                getActivity().setResult(Activity.RESULT_OK, intent);
            }

        }
    });
}

From source file:com.dycode.jepretstory.mediachooser.fragment.VideoFragment.java

private void setAdapter() {
    int count = mCursor.getCount();

    if (count > 0) {
        mDataColumnIndex = mCursor.getColumnIndex(MEDIA_DATA);
        int mIdColumnIndex = mCursor.getColumnIndex(MediaStore.Video.Media._ID);
        int mBucketColumnIndex = mCursor.getColumnIndex(MediaStore.Video.Media.BUCKET_ID);
        int resColumnIndex = mCursor.getColumnIndex(MediaStore.Video.Media.RESOLUTION);
        int durColumnIndex = mCursor.getColumnIndex(MediaStore.Video.Media.DURATION);

        //move position to first element
        mCursor.moveToFirst();/*  w  w  w.j av a2  s. co  m*/

        mGalleryModelList = new ArrayList<MediaModel>();
        for (int i = 0; i < count; i++) {
            mCursor.moveToPosition(i);
            String url = mCursor.getString(mDataColumnIndex);
            String id = mCursor.getString(mIdColumnIndex);
            String bucketId = mCursor.getString(mBucketColumnIndex);

            //mGalleryModelList.add(new MediaModel(url, false, MediaMode.VIDEO));

            //            boolean selected = false;
            //            if (mSelectedItems != null && mSelectedItems.size() > 0) {
            //               for(String currVidUrl: mSelectedItems) {
            //                  if (currVidUrl.equalsIgnoreCase(url)) {
            //                     selected = true;
            //                     break;
            //                  }
            //               }
            //            }

            MediaModel galleryModel = new MediaModel(bucketId, id, url, false, MediaType.VIDEO);
            if (mSelectedModels != null && mSelectedModels.size() > 0) {
                galleryModel.status = mSelectedModels.contains(galleryModel);
            }

            galleryModel.resolution = mCursor.getString(resColumnIndex);
            galleryModel.videoDuration = mCursor.getInt(durColumnIndex);

            mGalleryModelList.add(galleryModel);
        }

        mVideoAdapter = new GridViewAdapter(getActivity(), 0, mGalleryModelList, true);
        mVideoAdapter.videoFragment = this;
        mVideoGridView.setAdapter(mVideoAdapter);
        mVideoGridView.setOnScrollListener(this);

    } else {
        Toast.makeText(getActivity(), getActivity().getString(R.string.no_media_file_available),
                Toast.LENGTH_SHORT).show();

    }

    mVideoGridView.setOnItemLongClickListener(new OnItemLongClickListener() {

        @Override
        public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
            GridViewAdapter adapter = (GridViewAdapter) parent.getAdapter();
            MediaModel galleryModel = (MediaModel) adapter.getItem(position);
            File file = new File(galleryModel.url);
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setDataAndType(Uri.fromFile(file), "video/*");
            startActivity(intent);
            return false;
        }
    });

    mVideoGridView.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            // update the mStatus of each category in the adapter
            GridViewAdapter adapter = (GridViewAdapter) parent.getAdapter();
            MediaModel galleryModel = (MediaModel) adapter.getItem(position);

            if (!galleryModel.status) {
                long size = MediaChooserConstants.ChekcMediaFileSize(new File(galleryModel.url.toString()),
                        true);
                if (size != 0) {
                    Toast.makeText(getActivity(),
                            getActivity().getResources().getString(R.string.file_size_exeeded) + "  "
                                    + MediaChooserConstants.SELECTED_VIDEO_SIZE_IN_MB + " "
                                    + getActivity().getResources().getString(R.string.mb),
                            Toast.LENGTH_SHORT).show();
                    return;
                }

                if (MediaChooserConstants.ENFORCE_VIDEO_DURATION_LIMIT && galleryModel
                        .getVideoDurationInSeconds() > MediaChooserConstants.VIDEO_DURATION_LIMIT_IN_SECOND) {
                    String fmt = getActivity().getResources().getString(R.string.video_duration_limit_exeeded);
                    String msg = String.format(fmt, MediaChooserConstants.VIDEO_DURATION_LIMIT_IN_SECOND);
                    Toast.makeText(getActivity(), msg, Toast.LENGTH_SHORT).show();
                    return;
                }

                if (MediaChooserConstants.MAX_MEDIA_LIMIT == 1) {
                    //remove all first
                    if (mSelectedModels.size() >= 1) {

                        MediaModel selModel = (MediaModel) mSelectedModels.get(0);
                        selModel.status = false;

                        mSelectedModels.clear();
                        MediaChooserConstants.SELECTED_MEDIA_COUNT--;
                    }
                }

                if ((MediaChooserConstants.MAX_MEDIA_LIMIT == MediaChooserConstants.SELECTED_MEDIA_COUNT)) {
                    if (MediaChooserConstants.SELECTED_MEDIA_COUNT < 2) {
                        Toast.makeText(getActivity(),
                                getActivity().getResources().getString(R.string.max_limit_file) + "  "
                                        + MediaChooserConstants.SELECTED_MEDIA_COUNT + " "
                                        + getActivity().getResources().getString(R.string.file),
                                Toast.LENGTH_SHORT).show();
                        return;
                    } else {
                        Toast.makeText(getActivity(),
                                getActivity().getResources().getString(R.string.max_limit_file) + "  "
                                        + MediaChooserConstants.SELECTED_MEDIA_COUNT + " "
                                        + getActivity().getResources().getString(R.string.files),
                                Toast.LENGTH_SHORT).show();
                        return;
                    }
                }
            }

            // inverse the status
            galleryModel.status = !galleryModel.status;
            adapter.notifyDataSetChanged();

            if (galleryModel.status) {
                mSelectedModels.add(galleryModel);

                MediaChooserConstants.SELECTED_MEDIA_COUNT++;

            } else {
                mSelectedModels.remove(galleryModel);

                MediaChooserConstants.SELECTED_MEDIA_COUNT--;
            }

            if (mCallback != null) {

                mCallback.onVideoSelectedCount(mSelectedModels.size());

                if (galleryModel.status) {
                    mCallback.onVideoSelected(galleryModel);
                } else {
                    mCallback.onVideoUnselected(galleryModel);
                }

                Intent intent = new Intent();
                intent.putParcelableArrayListExtra("selectedVideos", mSelectedModels);
                getActivity().setResult(Activity.RESULT_OK, intent);
            }

        }
    });

}