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:com.oakesville.mythling.MediaActivity.java

protected void playItem(final Item item) {
    try {/*from  w  w  w . jav  a  2 s  .  c o m*/
        if (appSettings.isDevicePlayback()) {
            if (item.isMusic()) {
                Uri uri;
                if (item.isDownloaded()) {
                    uri = getDownload(item);
                } else {
                    String base = appSettings.getMythTvServicesBaseUrlWithCredentials() + "/Content/";
                    if (appSettings.isMythlingMediaServices()) {
                        uri = Uri.parse(base + "GetMusic?Id=" + item.getId());
                    } else {
                        uri = Uri.parse(base + "GetFile?StorageGroup=" + appSettings.getMusicStorageGroup()
                                + "&FileName=" + URLEncoder.encode(item.getFilePath(), "UTF-8"));
                    }
                }
                if (appSettings.isExternalMusicPlayer()) {
                    Intent intent = new Intent(android.content.Intent.ACTION_VIEW);
                    intent.setDataAndType(uri, "audio/*");
                    startActivity(intent);
                } else {
                    startProgress();
                    Toast.makeText(getApplicationContext(),
                            getString(R.string.playing) + ": " + item.getTitle(), Toast.LENGTH_LONG).show();
                    Intent playMusic = new Intent(this, MusicPlaybackService.class);
                    playMusic.setData(uri);
                    playMusic.putExtra(MusicPlaybackService.EXTRA_MESSENGER, new Messenger(new Handler() {
                        public void handleMessage(Message msg) {
                            if (msg.what == MusicPlaybackService.MESSAGE_PLAYER_PREPARED) {
                                stopProgress();
                                showStopMenuItem(true);
                            }
                        }
                    }));
                    playMusic.setAction(MusicPlaybackService.ACTION_PLAY);
                    startService(playMusic);
                }
            } else {
                if (item.isLiveTv()) {
                    TvShow tvShow = (TvShow) item;
                    if (tvShow.getEndTime()
                            .compareTo(Calendar.getInstance(TimeZone.getTimeZone("UTC")).getTime()) < 0) {
                        new AlertDialog.Builder(this).setIcon(android.R.drawable.ic_dialog_alert)
                                .setTitle(getString(R.string.live_tv))
                                .setMessage(getString(R.string.show_already_ended_) + "\n" + item.getTitle()
                                        + "\n" + tvShow.getChannelInfo() + "\n" + tvShow.getShowTimeInfo())
                                .setPositiveButton(R.string.ok, null).show();
                        onResume();
                        return;
                    }
                }
                String playbackNetwork = item.isDownloaded() ? PlaybackOptions.NETWORK_DOWNLOAD
                        : appSettings.getPlaybackNetwork();
                PlaybackOption playbackOption = appSettings.getPlaybackOptions().getOption(item.getType(),
                        item.getFormat(), playbackNetwork);
                if (appSettings.getMediaSettings().getViewType() != ViewType.list
                        && playbackOption.isAlways()) {
                    // detail or split mode -- no dialog if stream mode pref is set
                    startProgress();
                    if (playbackOption.isHls())
                        new StreamHlsTask(item).execute((URL) null);
                    else
                        playRawVideoStream(item);
                } else {
                    VideoPlaybackDialog dialog = getVideoPlaybackDialog(item);
                    dialog.show(getFragmentManager(), "StreamVideoDialog");
                }
            }
        } else {
            // frontend playback
            final FrontendPlayer player;
            if (item.isSearchResult()) {
                SearchResults searchResults = ((SearchActivity) this).searchResults;
                String basePath = null;
                if (item.isMusic())
                    basePath = searchResults.getMusicBase();
                else if (item.getStorageGroup() == null)
                    basePath = searchResults.getVideoBase();
                if (basePath != null)
                    player = new SocketFrontendPlayer(appSettings, basePath, item, getCharSet());
                else
                    player = new ServiceFrontendPlayer(appSettings, item);
            } else {
                if (item.isMusic() || item.getStorageGroup() == null) // frontend services require storage groups
                    player = new SocketFrontendPlayer(appSettings, mediaList.getBasePath(), item, getCharSet());
                else
                    player = new ServiceFrontendPlayer(appSettings, item);
            }

            if (player.checkIsPlaying()) {
                new AlertDialog.Builder(this).setIcon(android.R.drawable.ic_dialog_alert)
                        .setTitle(getString(R.string.interrupt)).setMessage(getString(R.string.stop_playback_))
                        .setPositiveButton(getString(R.string.yes), new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                player.stop();
                                startFrontendPlayback(item, player);
                            }
                        }).setNegativeButton(getString(R.string.no), null).show();
            } else {
                startFrontendPlayback(item, player);
            }
        }
    } catch (Exception ex) {
        stopProgress();
        onResume();
        Log.e(TAG, ex.getMessage(), ex);
        if (getAppSettings().isErrorReportingEnabled())
            new Reporter(ex).send();
        Toast.makeText(getApplicationContext(), getString(R.string.error_) + ex.toString(), Toast.LENGTH_LONG)
                .show();
    }
}

From source file:com.dwdesign.tweetings.util.Utils.java

public static void openImage(final Context context, final Uri uri, final boolean is_possibly_sensitive) {
    if (context == null || uri == null)
        return;//  w  w w .j  a va2  s  .  com
    final Intent intent = new Intent(INTENT_ACTION_VIEW_IMAGE);
    intent.setDataAndType(uri, "image/*");
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD_MR1) {
        intent.setClass(context, ImageViewerGLActivity.class);
    } else {
        intent.setClass(context, ImageViewerActivity.class);
    }
    final SharedPreferences prefs = context.getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE);
    if (context instanceof FragmentActivity && is_possibly_sensitive
            && !prefs.getBoolean(PREFERENCE_KEY_DISPLAY_SENSITIVE_CONTENTS, false)) {
        final FragmentActivity activity = (FragmentActivity) context;
        final FragmentManager fm = activity.getSupportFragmentManager();
        final DialogFragment fragment = new SensitiveContentWarningDialogFragment();
        final Bundle args = new Bundle();
        args.putParcelable(INTENT_KEY_URI, uri);
        fragment.setArguments(args);
        fragment.show(fm, "sensitive_content_warning");
    } else {
        context.startActivity(intent);
    }
}

From source file:com.quwu.xinwo.release.Release_Activity.java

@SuppressWarnings("unchecked")
protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    // TODO Auto-generated method stub
    super.onActivityResult(requestCode, resultCode, data);
    switch (requestCode) {
    case 20:/*from www .jav a2  s  .  co m*/
        if (data != null) {
            if (requestCode == 20) {
                String sheng = data.getExtras().getString("sheng");
                String shi = data.getExtras().getString("shi");
                twolevel_id = data.getExtras().getString("id1");
                three_id = data.getExtras().getString("id2");
                classifyText.setText(sheng + " " + shi + " ");
            }
        }
        break;
    case CLASSIFY:// ?
        if (data != null) {
            String selection_sort = data.getExtras().getString("selection_sort");// Activity ??
            classifyText.setText(selection_sort);
        }
        break;
    case KEYBOARD:// ?
        if (data != null) {
            list = (List<KeyBoardData>) data.getSerializableExtra("keyboard_data");
            for (int i = 0; i < list.size(); i++) {
                selling_price = list.get(i).getSelling_price();
                goods_value = list.get(i).getGoods_value();
                original_price = list.get(i).getOriginal_price();
                reserve_price = list.get(i).getReserve_price();
                freight = list.get(i).getFreight();
                check = list.get(i).isCheck();
            }
            if (cordelesBox.isChecked() == true) {
                if (selling_price != null) {
                    selling_priceEd.setText(selling_price);
                }
            } else if (auctionBox.isChecked() == true) {
                if (reserve_price != null) {
                    auction_retainPriceEd.setText(reserve_price);
                }
            } else if (rent_outBox.isChecked() == true) {
                if (goods_value != null && freight != null) {
                    rent_out_valueEd.setText(goods_value);
                    if (check == true) {
                        rent_out_freightEd.setText("0");
                    } else {
                        rent_out_freightEd.setText(freight);
                    }
                }
            }
        }
        break;
    case 10:// 
        if (data != null) {
            for (int i = 0; i < MyAdapter.mSelectedImage.size(); i++) {
                photolist.add((String) data.getExtras().get(String.valueOf(i)));
            }
        }
        break;
    case 2017:// ?
        Log.e("onActivityResult", "?");
        cropHelper.getDataFromCamera(data);
        break;
    case 2108:
        if (data != null && data.getParcelableExtra("data") != null) {
            for (int i = 0; i < times.size(); i++) {
                File f = new File(
                        OSUtils.getSdCardDirectory(getApplicationContext()) + times.get(i) + "head1.png");
                if (f.exists()) {
                    camearlist.add(
                            OSUtils.getSdCardDirectory(getApplicationContext()) + times.get(i) + "head1.png");
                }
            }
            for (int k = 0; k < camearlist.size() - 1; k++) {
                for (int j = camearlist.size() - 1; j > k; j--) {
                    if (camearlist.get(k).equals(camearlist.get(j))) {
                        camearlist.remove(j);
                    }
                }
            }
            for (int i = 0; i < camearlist.size(); i++) {
                photolist.add(camearlist.get(i));
            }
        }
        break;
    case CameraUtils.RequestCode.FLAG_REQUEST_CAMERA_VIDEO:// 
        if (data != null) {
            photolist.add(CameraUtils.CAMERA_VIDEO);
        }
        break;
    default:
        break;
    }
    for (int j = 0; j < photolist.size(); j++) {
        if (photolist.get(j).equals("drawable://" + R.drawable.fb_icn_carema)) {
            photolist.remove(j);
        }
        if (photolist.get(j).equals("drawable://" + R.drawable.fb_icn_video)) {
            photolist.remove(j);
        }
    }
    photolist.add("drawable://" + R.drawable.fb_icn_carema);
    photolist.add("drawable://" + R.drawable.fb_icn_video);
    for (int k = 0; k < photolist.size() - 1; k++) {
        for (int j = photolist.size() - 1; j > k; j--) {
            if (photolist.get(k).equals(photolist.get(j))) {
                photolist.remove(j);
            }
        }
    }
    adapter = new Release_GridViewAdapter(photolist, this, Release_Activity.this, times);
    gridView.setAdapter(adapter);
    gridView.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            if (photolist.get(position).equals("drawable://" + R.drawable.fb_icn_carema)) {
                int j = 0;
                for (int i = 0; i < photolist.size(); i++) {
                    if (photolist.get(i).equals(CameraUtils.CAMERA_VIDEO)) {
                        j++;
                    }
                }
                if (j == 1) {
                    if (photolist.size() < 13) {
                        Date dt = new Date();
                        time = dt.getTime();
                        times.add(time);
                        cropHelper = new CropHelper(Release_Activity.this,
                                OSUtils.getSdCardDirectory(getApplicationContext()) + time + "head1.png");
                        mTempPhotoPath = OSUtils.getSdCardDirectory(getApplicationContext()) + time
                                + "head1.png";
                        Release_Photo_Pop pop = new Release_Photo_Pop(Release_Activity.this, cropHelper,
                                mTempPhotoPath);
                        pop.showPopupWindow(gridView);
                    } else {
                        Toast.makeText(getApplicationContext(), "??~", 10).show();
                    }
                } else {
                    if (photolist.size() < 12) {
                        Date dt = new Date();
                        time = dt.getTime();
                        times.add(time);
                        cropHelper = new CropHelper(Release_Activity.this,
                                OSUtils.getSdCardDirectory(getApplicationContext()) + time + "head1.png");
                        mTempPhotoPath = OSUtils.getSdCardDirectory(getApplicationContext()) + time
                                + "head1.png";
                        Release_Photo_Pop pop = new Release_Photo_Pop(Release_Activity.this, cropHelper,
                                mTempPhotoPath);
                        pop.showPopupWindow(gridView);
                    } else {
                        Toast.makeText(getApplicationContext(), "??~", 10).show();
                    }
                }
            } else if (photolist.get(position).equals("drawable://" + R.drawable.fb_icn_video)) {

                int j = 0;
                for (int i = 0; i < photolist.size(); i++) {
                    if (photolist.get(i).equals(CameraUtils.CAMERA_VIDEO)) {
                        j++;
                    }
                }
                if (j != 1) {
                    CameraUtils.openCameraForVideo(Release_Activity.this);
                } else {
                    Toast.makeText(getApplicationContext(), "?~", 10).show();
                }
            } else if (photolist.get(position).equals(CameraUtils.CAMERA_VIDEO)) {// ?
                Intent intent = new Intent();
                intent.setAction(Intent.ACTION_VIEW); // ?
                Uri data = Uri.parse("file:///" + CameraUtils.CAMERA_VIDEO); // ???
                intent.setDataAndType(data, "video/mp4"); // ?
                startActivity(intent);
            }
        }
    });
    adapter.notifyDataSetChanged();
}

From source file:com.maskyn.fileeditorpro.activity.MainActivity.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int i = item.getItemId();
    if (mDrawerToggle.onOptionsItemSelected(item)) {
        Toast.makeText(getBaseContext(), "drawer click", Toast.LENGTH_SHORT).show();
        mDrawerLayout.closeDrawer(Gravity.END);
        return true;
    } else if (i == R.id.im_save_normaly) {
        saveTheFile(false);/*from   w  ww .  ja  va2s.co  m*/

    } else if (i == R.id.im_save_as) {
        saveTheFile(true);

    } else if (i == R.id.im_rename) {
        EditTextDialog.newInstance(EditTextDialog.Actions.Rename, greatUri.getFileName())
                .show(getFragmentManager().beginTransaction(), "dialog");
    } else if (i == R.id.im_undo) {
        mEditor.onTextContextMenuItem(ID_UNDO);

    } else if (i == R.id.im_redo) {
        mEditor.onTextContextMenuItem(ID_REDO);

    } else if (i == R.id.im_search) {
        FindTextDialog.newInstance(mEditor.getText().toString()).show(getFragmentManager().beginTransaction(),
                "dialog");
    } else if (i == R.id.im_cancel) {
        searchResult = null;
        invalidateOptionsMenu();

    } else if (i == R.id.im_replace) {
        replaceText(false);

    } else if (i == R.id.im_replace_all) {
        replaceText(true);

    } else if (i == R.id.im_next_item) {
        nextResult();

    } else if (i == R.id.im_previous_item) {
        previousResult();

    } else if (i == R.id.im_goto_line) {
        int min = mEditor.getLineUtils().firstReadLine();
        int max = mEditor.getLineUtils().lastReadLine();
        NumberPickerDialog.newInstance(NumberPickerDialog.Actions.GoToLine, min, min, max)
                .show(getFragmentManager().beginTransaction(), "dialog");
    } else if (i == R.id.im_view_it_on_browser) {
        Intent browserIntent;
        try {
            browserIntent = new Intent(Intent.ACTION_VIEW);
            browserIntent.setDataAndType(greatUri.getUri(), "*/*");
            startActivity(browserIntent);
        } catch (ActivityNotFoundException ex2) {
            //
        }

    } else if (i == R.id.im_view_markdown) {
        Intent browserIntent = new Intent(MainActivity.this, MarkdownActivity.class);
        browserIntent.putExtra("text", pageSystem.getAllText(mEditor.getText().toString()));
        startActivity(browserIntent);
    } else if (i == R.id.im_info) {
        FileInfoDialog.newInstance(greatUri.getUri()).show(getFragmentManager().beginTransaction(), "dialog");
    } else if (i == R.id.im_donate) {
        final String appPackageName = "com.maskyn.fileeditorpro";
        try {
            startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + appPackageName)));
        } catch (android.content.ActivityNotFoundException anfe) {
            startActivity(new Intent(Intent.ACTION_VIEW,
                    Uri.parse("https://play.google.com/store/apps/details?id=" + appPackageName)));
        }
    }
    return super.onOptionsItemSelected(item);
}

From source file:com.landenlabs.all_devtool.PackageFragment.java

/**
 * Load packages which are default (associated) with specific mime types.
 *
 * Use "adb shell dumpsys package r" to get full list
 *//*from ww w  . j  a va 2  s  . c o m*/
void loadDefaultPackages() {
    m_workList = new ArrayList<PackingItem>();

    String[] actions = { Intent.ACTION_SEND, Intent.ACTION_SEND, Intent.ACTION_SEND, Intent.ACTION_SEND,

            Intent.ACTION_VIEW, Intent.ACTION_VIEW, Intent.ACTION_VIEW, Intent.ACTION_VIEW, Intent.ACTION_VIEW,
            Intent.ACTION_VIEW, Intent.ACTION_VIEW, Intent.ACTION_VIEW,

            MediaStore.ACTION_IMAGE_CAPTURE, MediaStore.ACTION_VIDEO_CAPTURE,

            Intent.ACTION_CREATE_SHORTCUT };

    String[] types = { "audio/*", "video/*", "image/*", "text/plain",

            "application/pdf", "application/zip", "audio/*", "video/*", "image/*", "text/html", "text/plain",
            "text/csv",

            "image/png", "video/*",

            "" };

    long orderCnt = 1;
    for (int idx = 0; idx != actions.length; idx++) {
        String type = types[idx];
        Intent resolveIntent = new Intent(actions[idx]);

        if (!TextUtils.isEmpty(type)) {
            if (type.startsWith("audio/*")) {
                Uri uri = Uri.withAppendedPath(MediaStore.Audio.Media.INTERNAL_CONTENT_URI, "1");
                resolveIntent.setDataAndType(uri, type);
            } else if (type.startsWith("video/*")) {
                Uri uri = Uri.withAppendedPath(MediaStore.Video.Media.INTERNAL_CONTENT_URI, "1");
                resolveIntent.setDataAndType(uri, type);
            } else if (type.startsWith("text/")) {
                Uri uri = Uri.parse(Environment.getExternalStorageDirectory().getPath());
                resolveIntent.setDataAndType(uri, type);
            } else {
                resolveIntent.setType(type);
            }
        }

        PackageManager pm = getActivity().getPackageManager();

        // PackageManager.GET_RESOLVED_FILTER);  // or PackageManager.MATCH_DEFAULT_ONLY
        List<ResolveInfo> resolveList = pm.queryIntentActivities(resolveIntent, -1); // PackageManager.MATCH_DEFAULT_ONLY | PackageManager.GET_INTENT_FILTERS);

        if (resolveList != null) {
            String actType = type = Utils.last(actions[idx].split("[.]")) + ":" + type;
            for (ResolveInfo resolveInfo : resolveList) {
                ArrayListPairString pkgList = new ArrayListPairString();
                String appName = resolveInfo.activityInfo.loadLabel(pm).toString().trim();

                addList(pkgList, "Type", actType);
                String pkgName = resolveInfo.activityInfo.packageName;
                PackageInfo packInfo = null;
                try {
                    packInfo = pm.getPackageInfo(pkgName, 0);
                    addList(pkgList, "Version", packInfo.versionName);
                    addList(pkgList, "VerCode", String.valueOf(packInfo.versionCode));
                    addList(pkgList, "TargetSDK", String.valueOf(packInfo.applicationInfo.targetSdkVersion));
                    m_date.setTime(packInfo.firstInstallTime);
                    addList(pkgList, "Install First", s_timeFormat.format(m_date));
                    m_date.setTime(packInfo.lastUpdateTime);
                    addList(pkgList, "Install Last", s_timeFormat.format(m_date));
                    if (resolveInfo.filter != null) {
                        if (resolveInfo.filter.countDataSchemes() > 0) {
                            addList(pkgList, "Intent Scheme", "");
                            for (int sIdx = 0; sIdx != resolveInfo.filter.countDataSchemes(); sIdx++)
                                addList(pkgList, " ", resolveInfo.filter.getDataScheme(sIdx));
                        }
                        if (resolveInfo.filter.countActions() > 0) {
                            addList(pkgList, "Intent Action", "");
                            for (int aIdx = 0; aIdx != resolveInfo.filter.countActions(); aIdx++)
                                addList(pkgList, " ", resolveInfo.filter.getAction(aIdx));
                        }
                        if (resolveInfo.filter.countCategories() > 0) {
                            addList(pkgList, "Intent Category", "");
                            for (int cIdx = 0; cIdx != resolveInfo.filter.countCategories(); cIdx++)
                                addList(pkgList, " ", resolveInfo.filter.getCategory(cIdx));
                        }
                        if (resolveInfo.filter.countDataTypes() > 0) {
                            addList(pkgList, "Intent DataType", "");
                            for (int dIdx = 0; dIdx != resolveInfo.filter.countDataTypes(); dIdx++)
                                addList(pkgList, " ", resolveInfo.filter.getDataType(dIdx));
                        }
                    }
                    m_workList.add(
                            new PackingItem(pkgName.trim(), pkgList, packInfo, orderCnt++, appName, actType));
                } catch (Exception ex) {
                }
            }
        }

        if (false) {
            // TODO - look into this method, see loadCachedPackages
            int flags = PackageManager.GET_PROVIDERS;
            List<PackageInfo> packList = pm.getPreferredPackages(flags);
            if (packList != null) {
                for (int pkgIdx = 0; pkgIdx < packList.size(); pkgIdx++) {
                    PackageInfo packInfo = packList.get(pkgIdx);

                    // if (((packInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) == showSys) {
                    addPackageInfo(packInfo);
                    // }
                }
            }
        }
    }

    // getPreferredAppInfo();

    /*
    List<ProviderInfo> providerList = getActivity().getPackageManager().queryContentProviders(null, 0, 0);
    if (providerList != null) {
    for (ProviderInfo providerInfo : providerList) {
        String name = providerInfo.name;
        String pkg = providerInfo.packageName;
            
    }
    }
    */
}

From source file:at.ac.tuwien.caa.docscan.ui.CameraActivity.java

/**
 * Starts an intent with the last saved picture as data. This event is then handled by a user
 * defined app (like the image gallery app).
 *
 * @param path Path//from w  ww . j  a v a2 s .com
 * @param uri Uri
 */
@Override
public void onScanCompleted(String path, Uri uri) {

    try {

        if (uri != null) {

            Intent intent = new Intent(Intent.ACTION_VIEW);
            //                    I do not know why setData(uri) is not working with Marshmallows, it just opens one image (not the folder), with setData(Uri.fromFile) it is working:

            int currentApiVersion = android.os.Build.VERSION.SDK_INT;
            if (currentApiVersion >= Build.VERSION_CODES.M)
                intent.setDataAndType(Uri.fromFile(new File(path)), "image/*");
            else
                intent.setData(uri);
            //

            startActivity(intent);

        }

    } finally {
        mMediaScannerConnection.disconnect();
        mMediaScannerConnection = null;
    }

}

From source file:it.feio.android.omninotes.DetailFragment.java

private void initViewAttachments() {

    // Attachments position based on preferences
    if (prefs.getBoolean(Constants.PREF_ATTANCHEMENTS_ON_BOTTOM, false)) {
        attachmentsBelow.inflate();/*w ww  . j a v  a  2s.c  om*/
    } else {
        attachmentsAbove.inflate();
    }
    mGridView = (ExpandableHeightGridView) root.findViewById(R.id.gridview);

    // Some fields can be filled by third party application and are always shown
    mAttachmentAdapter = new AttachmentAdapter(mainActivity, noteTmp.getAttachmentsList(), mGridView);

    // Initialzation of gridview for images
    mGridView.setAdapter(mAttachmentAdapter);
    mGridView.autoresize();

    // Click events for images in gridview (zooms image)
    mGridView.setOnItemClickListener((parent, v, position, id) -> {
        Attachment attachment = (Attachment) parent.getAdapter().getItem(position);
        Uri uri = attachment.getUri();
        Intent attachmentIntent;
        if (Constants.MIME_TYPE_FILES.equals(attachment.getMime_type())) {

            attachmentIntent = new Intent(Intent.ACTION_VIEW);
            attachmentIntent.setDataAndType(uri, StorageHelper.getMimeType(mainActivity, attachment.getUri()));
            attachmentIntent
                    .addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            if (IntentChecker.isAvailable(mainActivity.getApplicationContext(), attachmentIntent, null)) {
                startActivity(attachmentIntent);
            } else {
                mainActivity.showMessage(R.string.feature_not_available_on_this_device, ONStyle.WARN);
            }

            // Media files will be opened in internal gallery
        } else if (Constants.MIME_TYPE_IMAGE.equals(attachment.getMime_type())
                || Constants.MIME_TYPE_SKETCH.equals(attachment.getMime_type())
                || Constants.MIME_TYPE_VIDEO.equals(attachment.getMime_type())) {
            // Title
            noteTmp.setTitle(getNoteTitle());
            noteTmp.setContent(getNoteContent());
            String title1 = TextHelper.parseTitleAndContent(mainActivity, noteTmp)[0].toString();
            // Images
            int clickedImage = 0;
            ArrayList<Attachment> images = new ArrayList<>();
            for (Attachment mAttachment : noteTmp.getAttachmentsList()) {
                if (Constants.MIME_TYPE_IMAGE.equals(mAttachment.getMime_type())
                        || Constants.MIME_TYPE_SKETCH.equals(mAttachment.getMime_type())
                        || Constants.MIME_TYPE_VIDEO.equals(mAttachment.getMime_type())) {
                    images.add(mAttachment);
                    if (mAttachment.equals(attachment)) {
                        clickedImage = images.size() - 1;
                    }
                }
            }
            // Intent
            attachmentIntent = new Intent(mainActivity, GalleryActivity.class);
            attachmentIntent.putExtra(Constants.GALLERY_TITLE, title1);
            attachmentIntent.putParcelableArrayListExtra(Constants.GALLERY_IMAGES, images);
            attachmentIntent.putExtra(Constants.GALLERY_CLICKED_IMAGE, clickedImage);
            startActivity(attachmentIntent);

        } else if (Constants.MIME_TYPE_AUDIO.equals(attachment.getMime_type())) {
            playback(v, attachment.getUri());
        }

    });

    mGridView.setOnItemLongClickListener((parent, v, position, id) -> {

        // To avoid deleting audio attachment during playback
        if (mPlayer != null)
            return false;

        List<String> items = Arrays.asList(getResources().getStringArray(R.array.attachments_actions));
        if (!Constants.MIME_TYPE_SKETCH.equals(mAttachmentAdapter.getItem(position).getMime_type())) {
            items = items.subList(0, items.size() - 1);
        }

        new MaterialDialog.Builder(mainActivity).title(mAttachmentAdapter.getItem(position).getName())
                .items(items.toArray(new String[items.size()]))
                .itemsCallback((materialDialog, view, i, charSequence) -> performAttachmentAction(position, i))
                .build().show();
        return true;
    });
}

From source file:com.adamas.client.android.MainActivity.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    } else if (id == R.id.action_scan_qr_code) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            IntentIntegrator integrator = new IntentIntegrator(this);
            integrator.initiateScan();// www  . ja v a 2  s . c o  m
        } else {
            checkCameraPermission();
        }
    } else if (id == R.id.action_delete_connector) {
        if (_connectorfragment != null) {
            _connectorfragment.deleteConnector(_selectedAdamasConnector);
        }
    } else if (id == R.id.action_add_connector_manually) {
        Intent intent = new Intent(this, AddConnectorActivity.class);
        startActivityForResult(intent, MANUALLY_ADD_CONNECTOR_REQUEST_CODE);
    } else if (id == R.id.action_edit_connector) {
        Intent intent = new Intent(this, EditConnectorActivity.class);
        Bundle mBundle = new Bundle();
        mBundle.putSerializable(EditConnectorActivity.ADAMAS_CONNECTOR, _selectedAdamasConnector);
        intent.putExtras(mBundle);
        startActivityForResult(intent, MANUALLY_EDIT_CONNECTOR_REQUEST_CODE);
    } else if (id == R.id.action_import_connector_from_text) {
        Intent intent = new Intent(this, ImportTextActivity.class);
        startActivityForResult(intent, IMPORT_FROM_TEXT_REQUEST_CODE);
    } else if (id == R.id.action_import_connector_from_image) {
        if (false) {
            FileChooser fileChooser = new FileChooser(this);
            fileChooser.setFileListener(new FileChooser.FileSelectedListener() {
                @Override
                public void fileSelected(final File file) {
                    String name = file.getAbsolutePath();
                    name = name;
                }
            });
            fileChooser.showDialog();
        } else {
            // this is much better
            Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
            Uri uri = Uri.parse(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
                    .getAbsolutePath());
            intent.setDataAndType(uri, "image/jpeg");
            startActivityForResult(Intent.createChooser(intent, getString(R.string.open)),
                    IMPORT_FROM_FILE_REQUEST_CODE);
        }
    }

    return super.onOptionsItemSelected(item);
}

From source file:com.github.michalbednarski.intentslab.editor.IntentGeneralFragment.java

@Override
public void updateEditedIntent(Intent editedIntent) {
    // Intent action

    if (mAvailbleActions != null) {
        editedIntent.setAction((String) mActionsSpinner.getSelectedItem());
    } else {/*from w w w  . j  a v  a2s . c o  m*/
        String action = mActionText.getText().toString();
        if ("".equals(action)) {
            action = null;
        }
        editedIntent.setAction(action);
    }

    // Categories
    {
        // Clear categories (why there's no api for this)
        Set<String> origCategories = editedIntent.getCategories();
        if (origCategories != null) {
            for (String category : origCategories.toArray(new String[origCategories.size()])) {
                editedIntent.removeCategory(category);
            }
        }
    }
    // Fill categories
    if (mCategoryCheckBoxes != null) {
        // Fill categories from checkboxes
        for (CheckBox cb : mCategoryCheckBoxes) {
            String category = (String) cb.getTag();
            if (cb.isChecked()) {
                editedIntent.addCategory(category);
            }
        }
    } else {
        // Fill categories from textfields
        for (TextView categoryTextView : mCategoryTextInputs) {
            editedIntent.addCategory(categoryTextView.getText().toString());
        }
    }

    // Intent data (Uri) and type (MIME)
    String data = mDataText.getText().toString();
    editedIntent.setDataAndType(data.equals("") ? null : Uri.parse(data), getDataType());

    // Package name
    {
        String packageName = mPackageNameText.getText().toString();
        if ("".equals(packageName)) {
            editedIntent.setPackage(null);
        } else {
            editedIntent.setPackage(packageName);
        }
    }

    // Set component for explicit intent
    updateIntentComponent();
}

From source file:com.dycody.android.idealnote.DetailFragment.java

private void initViewAttachments() {

    // Attachments position based on preferences
    if (prefs.getBoolean(Constants.PREF_ATTANCHEMENTS_ON_BOTTOM, false)) {
        attachmentsBelow.inflate();/*from   ww  w  .  j a  va 2s . c  om*/
    } else {
        attachmentsAbove.inflate();
    }
    mGridView = (ExpandableHeightGridView) root.findViewById(R.id.gridview);

    // Some fields can be filled by third party application and are always shown
    mAttachmentAdapter = new AttachmentAdapter(mainActivity, noteTmp.getAttachmentsList(), mGridView);

    // Initialzation of gridview for images
    mGridView.setAdapter(mAttachmentAdapter);
    mGridView.autoresize();

    // Click events for images in gridview (zooms image)
    mGridView.setOnItemClickListener((parent, v, position, id) -> {
        Attachment attachment = (Attachment) parent.getAdapter().getItem(position);
        Uri uri = attachment.getUri();
        Intent attachmentIntent;
        if (Constants.MIME_TYPE_FILES.equals(attachment.getMime_type())) {

            attachmentIntent = new Intent(Intent.ACTION_VIEW);
            attachmentIntent.setDataAndType(uri, StorageHelper.getMimeType(mainActivity, attachment.getUri()));
            attachmentIntent
                    .addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            if (IntentChecker.isAvailable(mainActivity.getApplicationContext(), attachmentIntent, null)) {
                startActivity(attachmentIntent);
            } else {
                Toast.makeText(getActivity(), R.string.feature_not_available_on_this_device, Toast.LENGTH_SHORT)
                        .show();
                //mainActivity.showMessage(R.string.feature_not_available_on_this_device, ONStyle.WARN);
            }

            // Media files will be opened in internal gallery
        } else if (Constants.MIME_TYPE_IMAGE.equals(attachment.getMime_type())
                || Constants.MIME_TYPE_SKETCH.equals(attachment.getMime_type())
                || Constants.MIME_TYPE_VIDEO.equals(attachment.getMime_type())) {
            // Title
            noteTmp.setTitle(getNoteTitle());
            noteTmp.setContent(getNoteContent());
            String title1 = TextHelper.parseTitleAndContent(mainActivity, noteTmp)[0].toString();
            // Images
            int clickedImage = 0;
            ArrayList<Attachment> images = new ArrayList<>();
            for (Attachment mAttachment : noteTmp.getAttachmentsList()) {
                if (Constants.MIME_TYPE_IMAGE.equals(mAttachment.getMime_type())
                        || Constants.MIME_TYPE_SKETCH.equals(mAttachment.getMime_type())
                        || Constants.MIME_TYPE_VIDEO.equals(mAttachment.getMime_type())) {
                    images.add(mAttachment);
                    if (mAttachment.equals(attachment)) {
                        clickedImage = images.size() - 1;
                    }
                }
            }
            // Intent
            attachmentIntent = new Intent(mainActivity, GalleryActivity.class);
            attachmentIntent.putExtra(Constants.GALLERY_TITLE, title1);
            attachmentIntent.putParcelableArrayListExtra(Constants.GALLERY_IMAGES, images);
            attachmentIntent.putExtra(Constants.GALLERY_CLICKED_IMAGE, clickedImage);
            startActivity(attachmentIntent);

        } else if (Constants.MIME_TYPE_AUDIO.equals(attachment.getMime_type())) {
            playback(v, attachment.getUri());
        }

    });

    mGridView.setOnItemLongClickListener((parent, v, position, id) -> {
        // To avoid deleting audio attachment during playback
        if (mPlayer != null)
            return false;
        List<String> items = Arrays.asList(getResources().getStringArray(R.array.attachments_actions));
        if (!Constants.MIME_TYPE_SKETCH.equals(mAttachmentAdapter.getItem(position).getMime_type())) {
            items = items.subList(0, items.size() - 1);
        }
        Attachment attachment = mAttachmentAdapter.getItem(position);
        new MaterialDialog.Builder(mainActivity)
                .title(attachment.getName() + " (" + AttachmentsHelper.getSize(attachment) + ")")
                .items(items.toArray(new String[items.size()]))
                .itemsCallback((materialDialog, view, i, charSequence) -> performAttachmentAction(position, i))
                .build().show();
        return true;
    });
}