Example usage for android.content Intent ACTION_MEDIA_SCANNER_SCAN_FILE

List of usage examples for android.content Intent ACTION_MEDIA_SCANNER_SCAN_FILE

Introduction

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

Prototype

String ACTION_MEDIA_SCANNER_SCAN_FILE

To view the source code for android.content Intent ACTION_MEDIA_SCANNER_SCAN_FILE.

Click Source Link

Document

Broadcast Action: Request the media scanner to scan a file and add it to the media database.

Usage

From source file:freed.viewer.dngconvert.DngConvertingFragment.java

private void convertRawToDng(File file) {
    byte[] data = null;
    try {/*from  ww  w. j av a 2  s  . c om*/
        data = RawToDng.readFile(file);
        Log.d("Main", "Filesize: " + data.length + " File:" + file.getAbsolutePath());

    } catch (IOException ex) {
        ex.printStackTrace();
    }
    String out = null;
    if (file.getName().endsWith(FileEnding.RAW))
        out = file.getAbsolutePath().replace(FileEnding.RAW, FileEnding.DNG);
    if (file.getName().endsWith(FileEnding.BAYER))
        out = file.getAbsolutePath().replace(FileEnding.BAYER, FileEnding.DNG);
    RawToDng dng = RawToDng.GetInstance();
    String intsd = StringUtils.GetInternalSDCARD();
    if (VERSION.SDK_INT <= VERSION_CODES.LOLLIPOP || file.getAbsolutePath().contains(intsd))
        dng.setBayerData(data, out);
    else {
        DocumentFile df = ((ActivityInterface) getActivity()).getFreeDcamDocumentFolder();
        DocumentFile wr = df.createFile("image/dng", file.getName().replace(FileEnding.JPG, FileEnding.DNG));
        ParcelFileDescriptor pfd = null;
        try {

            pfd = getContext().getContentResolver().openFileDescriptor(wr.getUri(), "rw");
        } catch (FileNotFoundException | IllegalArgumentException ex) {
            ex.printStackTrace();
        }
        if (pfd != null) {
            dng.SetBayerDataFD(data, pfd, file.getName());
            try {
                pfd.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            pfd = null;
        }
    }
    dng.setExifData(100, 0, 0, 0, 0, "", "0", 0);
    if (fakeGPS.isChecked())
        dng.SetGpsData(Altitude, Latitude, Longitude, Provider, gpsTime);
    dng.WriteDngWithProfile(dngprofile);
    data = null;
    Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
    intent.setData(Uri.fromFile(file));
    getActivity().sendBroadcast(intent);
    if (filesToConvert.length == 1) {

        final Bitmap map = new RawUtils().UnPackRAW(out);
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                imageView.setImageBitmap(map);
            }
        });
    }
}

From source file:com.learnncode.mediachooser.activity.HomeScreenMediaChooser.java

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    super.onActivityResult(requestCode, resultCode, data);

    if (resultCode == Activity.RESULT_OK) {

        if (requestCode == MediaChooserConstants.BUCKET_SELECT_IMAGE_CODE) {
            addMedia(mSelectedImage, data.getStringArrayListExtra("list"));

        } else if (requestCode == MediaChooserConstants.BUCKET_SELECT_VIDEO_CODE) {
            addMedia(mSelectedVideo, data.getStringArrayListExtra("list"));

        } else if (requestCode == MediaChooserConstants.CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {

            sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, fileUri));
            final AlertDialog alertDialog = MediaChooserConstants.getDialog(mContext).create();
            alertDialog.show();//from  w w  w.j a v  a2s .  c o m

            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    //Do something after 2000ms
                    String fileUriString = fileUri.toString().replaceFirst("file:///", "/").trim();
                    Fragment fragment = mViewPagerAdapter.getItem(0);

                    if (fragment instanceof ImageFragment) {
                        ImageFragment imageFragment = (ImageFragment) fragment;

                        if (imageFragment != null) {
                            imageFragment.addNewEntry(fileUriString);
                        }
                    } else {

                        ImageFragment imageFragment = (ImageFragment) mViewPagerAdapter.getItem(1);

                        if (imageFragment != null) {
                            imageFragment.addNewEntry(fileUriString);
                        }
                    }

                    alertDialog.dismiss();
                }
            }, 5000);

        } else if (requestCode == MediaChooserConstants.CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) {

            sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, fileUri));

            final AlertDialog alertDialog = MediaChooserConstants.getDialog(mContext).create();
            alertDialog.show();
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    //Do something after 2000ms
                    String fileUriString = fileUri.toString().replaceFirst("file:///", "/").trim();

                    Fragment fragment = mViewPagerAdapter.getItem(0);
                    if (fragment instanceof VideoFragment) {
                        VideoFragment videoFragment = (VideoFragment) fragment;

                        if (videoFragment != null) {
                            videoFragment.addNewEntry(fileUriString);
                        }
                    } else {

                        VideoFragment videoFragment = (VideoFragment) mViewPagerAdapter.getItem(1);

                        if (videoFragment != null) {
                            videoFragment.addNewEntry(fileUriString);
                        }
                    }
                    alertDialog.dismiss();
                }
            }, 5000);
        }
    }
}

From source file:com.example.de.taomi2.mediachooser.activity.HomeFragmentActivity.java

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    if (requestCode == MediaChooserConstants.CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) {
        if (resultCode == RESULT_OK) {

            sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, fileUri));
            final AlertDialog alertDialog = MediaChooserConstants.getDialog(HomeFragmentActivity.this).create();
            alertDialog.show();/*from  www .  j a  v  a  2s .co  m*/
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    //Do something after 5000ms
                    String fileUriString = fileUri.toString().replaceFirst("file:///", "/").trim();
                    android.support.v4.app.FragmentManager fragmentManager = getSupportFragmentManager();
                    VideoFragment videoFragment = (VideoFragment) fragmentManager.findFragmentByTag("tab2");
                    //                  
                    if (videoFragment == null) {
                        VideoFragment newVideoFragment = new VideoFragment();
                        newVideoFragment.addItem(fileUriString);

                    } else {
                        videoFragment.addItem(fileUriString);
                    }
                    alertDialog.cancel();
                }
            }, 5000);

        } else if (resultCode == RESULT_CANCELED) {
            // User cancelled the video capture
        } else {
            // Video capture failed, advise user
        }
    } else if (requestCode == MediaChooserConstants.CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {
        if (resultCode == RESULT_OK) {

            sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, fileUri));

            final AlertDialog alertDialog = MediaChooserConstants.getDialog(HomeFragmentActivity.this).create();
            alertDialog.show();
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    //Do something after 5000ms
                    String fileUriString = fileUri.toString().replaceFirst("file:///", "/").trim();
                    android.support.v4.app.FragmentManager fragmentManager = getSupportFragmentManager();
                    ImageFragment imageFragment = (ImageFragment) fragmentManager.findFragmentByTag("tab1");
                    if (imageFragment == null) {
                        ImageFragment newImageFragment = new ImageFragment();
                        newImageFragment.addItem(fileUriString);

                    } else {
                        imageFragment.addItem(fileUriString);
                    }
                    alertDialog.cancel();
                }
            }, 5000);
        }
    }
}

From source file:vn.tungdx.mediapicker.activities.HomeFragmentActivity.java

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    if (requestCode == MediaChooserConstants.CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) {
        if (resultCode == RESULT_OK) {

            sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, fileUri));
            final AlertDialog alertDialog = MediaChooserConstants.getDialog(HomeFragmentActivity.this).create();
            alertDialog.show();// ww  w  .j  a  va2  s  . com
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    // Do something after 5000ms
                    String fileUriString = fileUri.toString().replaceFirst("file:///", "/").trim();
                    android.support.v4.app.FragmentManager fragmentManager = getSupportFragmentManager();
                    VideoFragment videoFragment = (VideoFragment) fragmentManager.findFragmentByTag("tab2");
                    //
                    if (videoFragment == null) {
                        VideoFragment newVideoFragment = new VideoFragment();
                        newVideoFragment.addItem(fileUriString);

                    } else {
                        videoFragment.addItem(fileUriString);
                    }
                    alertDialog.cancel();
                }
            }, 5000);

        } else if (resultCode == RESULT_CANCELED) {
            // User cancelled the video capture
        } else {
            // Video capture failed, advise user
        }
    } else if (requestCode == MediaChooserConstants.CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {
        if (resultCode == RESULT_OK) {

            sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, fileUri));

            final AlertDialog alertDialog = MediaChooserConstants.getDialog(HomeFragmentActivity.this).create();
            alertDialog.show();
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    // Do something after 5000ms
                    String fileUriString = fileUri.toString().replaceFirst("file:///", "/").trim();
                    android.support.v4.app.FragmentManager fragmentManager = getSupportFragmentManager();
                    ImageFragment imageFragment = (ImageFragment) fragmentManager.findFragmentByTag("tab1");
                    if (imageFragment == null) {
                        ImageFragment newImageFragment = new ImageFragment();
                        newImageFragment.addItem(fileUriString);

                    } else {
                        imageFragment.addItem(fileUriString);
                    }
                    alertDialog.cancel();
                }
            }, 5000);
        }
    }
}

From source file:com.ryan.ryanreader.reddit.prepared.RedditPreparedPost.java

public static void onActionMenuItemSelected(final RedditPreparedPost post, final Fragment fragmentParent,
        final Action action) {

    final Activity activity = fragmentParent.getSupportActivity();

    switch (action) {

    case UPVOTE:/*from w w w . j av  a 2  s .c om*/
        post.action(activity, RedditAPI.RedditAction.UPVOTE);
        break;

    case DOWNVOTE:
        post.action(activity, RedditAPI.RedditAction.DOWNVOTE);
        break;

    case UNVOTE:
        post.action(activity, RedditAPI.RedditAction.UNVOTE);
        break;

    case SAVE:
        post.action(activity, RedditAPI.RedditAction.SAVE);
        break;

    case UNSAVE:
        post.action(activity, RedditAPI.RedditAction.UNSAVE);
        break;

    case HIDE:
        post.action(activity, RedditAPI.RedditAction.HIDE);
        break;

    case UNHIDE:
        post.action(activity, RedditAPI.RedditAction.UNHIDE);
        break;

    case REPORT:

        new AlertDialog.Builder(activity).setTitle(R.string.action_report)
                .setMessage(R.string.action_report_sure)
                .setPositiveButton(R.string.action_report, new DialogInterface.OnClickListener() {
                    public void onClick(final DialogInterface dialog, final int which) {
                        post.action(activity, RedditAPI.RedditAction.REPORT);
                        // TODO update the view to show the result
                        // TODO don't forget, this also hides
                    }
                }).setNegativeButton(R.string.dialog_cancel, null).show();

        break;

    case EXTERNAL: {
        final Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setData(Uri.parse(post.url));
        activity.startActivity(intent);
        break;
    }

    case SELFTEXT_LINKS: {

        final HashSet<String> linksInComment = LinkHandler
                .computeAllLinks(StringEscapeUtils.unescapeHtml4(post.src.selftext));

        if (linksInComment.isEmpty()) {
            General.quickToast(activity, R.string.error_toast_no_urls_in_self);

        } else {

            final String[] linksArr = linksInComment.toArray(new String[linksInComment.size()]);

            final AlertDialog.Builder builder = new AlertDialog.Builder(activity);
            builder.setItems(linksArr, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    LinkHandler.onLinkClicked(activity, linksArr[which], false, post.src);
                    dialog.dismiss();
                }
            });

            final AlertDialog alert = builder.create();
            alert.setTitle(R.string.action_selftext_links);
            alert.setCanceledOnTouchOutside(true);
            alert.show();
        }

        break;
    }

    case SAVE_IMAGE: {

        final RedditAccount anon = RedditAccountManager.getAnon();

        CacheManager.getInstance(activity)
                .makeRequest(new CacheRequest(General.uriFromString(post.imageUrl), anon, null,
                        Constants.Priority.IMAGE_VIEW, 0, CacheRequest.DownloadType.IF_NECESSARY,
                        Constants.FileType.IMAGE, false, false, false, activity) {

                    @Override
                    protected void onCallbackException(Throwable t) {
                        BugReportActivity.handleGlobalError(context, t);
                    }

                    @Override
                    protected void onDownloadNecessary() {
                        General.quickToast(context, R.string.download_downloading);
                    }

                    @Override
                    protected void onDownloadStarted() {
                    }

                    @Override
                    protected void onFailure(RequestFailureType type, Throwable t, StatusLine status,
                            String readableMessage) {
                        final RRError error = General.getGeneralErrorForFailure(context, type, t, status);
                        General.showResultDialog(activity, error);
                    }

                    @Override
                    protected void onProgress(long bytesRead, long totalBytes) {
                    }

                    @Override
                    protected void onSuccess(CacheManager.ReadableCacheFile cacheFile, long timestamp,
                            UUID session, boolean fromCache, String mimetype) {

                        File dst = new File(
                                Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
                                General.uriFromString(post.imageUrl).getPath());

                        if (dst.exists()) {
                            int count = 0;

                            while (dst.exists()) {
                                count++;
                                dst = new File(
                                        Environment.getExternalStoragePublicDirectory(
                                                Environment.DIRECTORY_PICTURES),
                                        count + "_"
                                                + General.uriFromString(post.imageUrl).getPath().substring(1));
                            }
                        }

                        try {
                            General.copyFile(cacheFile.getInputStream(), dst);
                        } catch (IOException e) {
                            notifyFailure(RequestFailureType.STORAGE, e, null, "Could not copy file");
                            return;
                        }

                        activity.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
                                Uri.parse("file://" + dst.getAbsolutePath())));

                        General.quickToast(context, context.getString(R.string.action_save_image_success) + " "
                                + dst.getAbsolutePath());
                    }
                });

        break;
    }

    case SHARE: {

        final Intent mailer = new Intent(Intent.ACTION_SEND);
        mailer.setType("text/plain");
        mailer.putExtra(Intent.EXTRA_SUBJECT, post.title);
        mailer.putExtra(Intent.EXTRA_TEXT, post.url);
        activity.startActivity(Intent.createChooser(mailer, activity.getString(R.string.action_share)));
        break;
    }

    case SHARE_COMMENTS: {

        final Intent mailer = new Intent(Intent.ACTION_SEND);
        mailer.setType("text/plain");
        mailer.putExtra(Intent.EXTRA_SUBJECT, "Comments for " + post.title);
        mailer.putExtra(Intent.EXTRA_TEXT,
                Constants.Reddit.getUri(Constants.Reddit.PATH_COMMENTS + post.idAlone).toString());
        activity.startActivity(
                Intent.createChooser(mailer, activity.getString(R.string.action_share_comments)));
        break;
    }

    case COPY: {

        ClipboardManager manager = (ClipboardManager) activity.getSystemService(Context.CLIPBOARD_SERVICE);
        manager.setText(post.url);
        break;
    }

    case GOTO_SUBREDDIT: {

        final RedditSubreddit subreddit = new RedditSubreddit("/r/" + post.src.subreddit,
                "/r/" + post.src.subreddit, true);

        final Intent intent = new Intent(activity, PostListingActivity.class);
        intent.putExtra("subreddit", subreddit);
        activity.startActivityForResult(intent, 1);
        break;
    }

    case USER_PROFILE:
        UserProfileDialog.newInstance(post.src.author).show(activity);
        break;

    case PROPERTIES:
        PostPropertiesDialog.newInstance(post.src).show(activity);
        break;

    case COMMENTS:
        ((RedditPostView.PostSelectionListener) fragmentParent).onPostCommentsSelected(post);
        break;

    case LINK:
        ((RedditPostView.PostSelectionListener) fragmentParent).onPostSelected(post);
        break;

    case COMMENTS_SWITCH:
        if (!(activity instanceof MainActivity))
            activity.finish();
        ((RedditPostView.PostSelectionListener) fragmentParent).onPostCommentsSelected(post);
        break;

    case LINK_SWITCH:
        if (!(activity instanceof MainActivity))
            activity.finish();
        ((RedditPostView.PostSelectionListener) fragmentParent).onPostSelected(post);
        break;

    case ACTION_MENU:
        showActionMenu(activity, fragmentParent, post);
        break;

    case REPLY:
        final Intent intent = new Intent(activity, CommentReplyActivity.class);
        intent.putExtra("parentIdAndType", post.idAndType);
        activity.startActivity(intent);
        break;
    }
}

From source file:com.remobile.file.LocalFilesystem.java

/**
* Send broadcast of new file so files appear over MTP
*///from w  ww . ja va  2s  . co m
private void broadcastNewFile(Uri nativeUri) {
    Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, nativeUri);
    context.sendBroadcast(intent);
}

From source file:org.lol.reddit.reddit.prepared.RedditPreparedPost.java

public static void onActionMenuItemSelected(final RedditPreparedPost post, final Activity activity,
        final Action action) {

    switch (action) {

    case UPVOTE:/*  ww  w .  ja  v  a  2  s  . c o  m*/
        post.action(activity, RedditAPI.RedditAction.UPVOTE);
        break;

    case DOWNVOTE:
        post.action(activity, RedditAPI.RedditAction.DOWNVOTE);
        break;

    case UNVOTE:
        post.action(activity, RedditAPI.RedditAction.UNVOTE);
        break;

    case SAVE:
        post.action(activity, RedditAPI.RedditAction.SAVE);
        break;

    case UNSAVE:
        post.action(activity, RedditAPI.RedditAction.UNSAVE);
        break;

    case HIDE:
        post.action(activity, RedditAPI.RedditAction.HIDE);
        break;

    case UNHIDE:
        post.action(activity, RedditAPI.RedditAction.UNHIDE);
        break;

    case REPORT:

        new AlertDialog.Builder(activity).setTitle(R.string.action_report)
                .setMessage(R.string.action_report_sure)
                .setPositiveButton(R.string.action_report, new DialogInterface.OnClickListener() {
                    public void onClick(final DialogInterface dialog, final int which) {
                        post.action(activity, RedditAPI.RedditAction.REPORT);
                        // TODO update the view to show the result
                        // TODO don't forget, this also hides
                    }
                }).setNegativeButton(R.string.dialog_cancel, null).show();

        break;

    case EXTERNAL: {
        final Intent intent = new Intent(Intent.ACTION_VIEW);
        String url = (activity instanceof WebViewActivity) ? ((WebViewActivity) activity).getCurrentUrl()
                : post.url;
        intent.setData(Uri.parse(url));
        activity.startActivity(intent);
        break;
    }

    case SELFTEXT_LINKS: {

        final HashSet<String> linksInComment = LinkHandler
                .computeAllLinks(StringEscapeUtils.unescapeHtml4(post.src.selftext));

        if (linksInComment.isEmpty()) {
            General.quickToast(activity, R.string.error_toast_no_urls_in_self);

        } else {

            final String[] linksArr = linksInComment.toArray(new String[linksInComment.size()]);

            final AlertDialog.Builder builder = new AlertDialog.Builder(activity);
            builder.setItems(linksArr, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    LinkHandler.onLinkClicked(activity, linksArr[which], false, post.src);
                    dialog.dismiss();
                }
            });

            final AlertDialog alert = builder.create();
            alert.setTitle(R.string.action_selftext_links);
            alert.setCanceledOnTouchOutside(true);
            alert.show();
        }

        break;
    }

    case SAVE_IMAGE: {

        final RedditAccount anon = RedditAccountManager.getAnon();

        CacheManager.getInstance(activity)
                .makeRequest(new CacheRequest(General.uriFromString(post.imageUrl), anon, null,
                        Constants.Priority.IMAGE_VIEW, 0, CacheRequest.DownloadType.IF_NECESSARY,
                        Constants.FileType.IMAGE, false, false, false, activity) {

                    @Override
                    protected void onCallbackException(Throwable t) {
                        BugReportActivity.handleGlobalError(context, t);
                    }

                    @Override
                    protected void onDownloadNecessary() {
                        General.quickToast(context, R.string.download_downloading);
                    }

                    @Override
                    protected void onDownloadStarted() {
                    }

                    @Override
                    protected void onFailure(RequestFailureType type, Throwable t, StatusLine status,
                            String readableMessage) {
                        final RRError error = General.getGeneralErrorForFailure(context, type, t, status,
                                url.toString());
                        General.showResultDialog(activity, error);
                    }

                    @Override
                    protected void onProgress(long bytesRead, long totalBytes) {
                    }

                    @Override
                    protected void onSuccess(CacheManager.ReadableCacheFile cacheFile, long timestamp,
                            UUID session, boolean fromCache, String mimetype) {

                        File dst = new File(
                                Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
                                General.uriFromString(post.imageUrl).getPath());

                        if (dst.exists()) {
                            int count = 0;

                            while (dst.exists()) {
                                count++;
                                dst = new File(
                                        Environment.getExternalStoragePublicDirectory(
                                                Environment.DIRECTORY_PICTURES),
                                        count + "_"
                                                + General.uriFromString(post.imageUrl).getPath().substring(1));
                            }
                        }

                        try {
                            final InputStream cacheFileInputStream = cacheFile.getInputStream();

                            if (cacheFileInputStream == null) {
                                notifyFailure(RequestFailureType.CACHE_MISS, null, null,
                                        "Could not find cached image");
                                return;
                            }

                            General.copyFile(cacheFileInputStream, dst);

                        } catch (IOException e) {
                            notifyFailure(RequestFailureType.STORAGE, e, null, "Could not copy file");
                            return;
                        }

                        activity.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
                                Uri.parse("file://" + dst.getAbsolutePath())));

                        General.quickToast(context, context.getString(R.string.action_save_image_success) + " "
                                + dst.getAbsolutePath());
                    }
                });

        break;
    }

    case SHARE: {

        final Intent mailer = new Intent(Intent.ACTION_SEND);
        mailer.setType("text/plain");
        mailer.putExtra(Intent.EXTRA_SUBJECT, post.title);
        mailer.putExtra(Intent.EXTRA_TEXT, post.url);
        activity.startActivity(Intent.createChooser(mailer, activity.getString(R.string.action_share)));
        break;
    }

    case SHARE_COMMENTS: {

        final Intent mailer = new Intent(Intent.ACTION_SEND);
        mailer.setType("text/plain");
        mailer.putExtra(Intent.EXTRA_SUBJECT, "Comments for " + post.title);
        mailer.putExtra(Intent.EXTRA_TEXT,
                Constants.Reddit.getUri(Constants.Reddit.PATH_COMMENTS + post.idAlone).toString());
        activity.startActivity(
                Intent.createChooser(mailer, activity.getString(R.string.action_share_comments)));
        break;
    }

    case COPY: {

        ClipboardManager manager = (ClipboardManager) activity.getSystemService(Context.CLIPBOARD_SERVICE);
        manager.setText(post.url);
        break;
    }

    case GOTO_SUBREDDIT: {

        try {
            final Intent intent = new Intent(activity, PostListingActivity.class);
            intent.setData(SubredditPostListURL.getSubreddit(post.src.subreddit).generateJsonUri());
            activity.startActivityForResult(intent, 1);

        } catch (RedditSubreddit.InvalidSubredditNameException e) {
            Toast.makeText(activity, R.string.invalid_subreddit_name, Toast.LENGTH_LONG).show();
        }

        break;
    }

    case USER_PROFILE:
        LinkHandler.onLinkClicked(activity, new UserProfileURL(post.src.author).toString());
        break;

    case PROPERTIES:
        PostPropertiesDialog.newInstance(post.src).show(activity);
        break;

    case COMMENTS:
        ((RedditPostView.PostSelectionListener) activity).onPostCommentsSelected(post);
        break;

    case LINK:
        ((RedditPostView.PostSelectionListener) activity).onPostSelected(post);
        break;

    case COMMENTS_SWITCH:
        if (!(activity instanceof MainActivity))
            activity.finish();
        ((RedditPostView.PostSelectionListener) activity).onPostCommentsSelected(post);
        break;

    case LINK_SWITCH:
        if (!(activity instanceof MainActivity))
            activity.finish();
        ((RedditPostView.PostSelectionListener) activity).onPostSelected(post);
        break;

    case ACTION_MENU:
        showActionMenu(activity, post);
        break;

    case REPLY:
        final Intent intent = new Intent(activity, CommentReplyActivity.class);
        intent.putExtra("parentIdAndType", post.idAndType);
        activity.startActivity(intent);
        break;
    }
}

From source file:mediachooser.activity.HomeFragmentActivity.java

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    if (requestCode == MediaChooserConstants.CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) {
        if (resultCode == RESULT_OK) {

            sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, fileUri));
            final AlertDialog alertDialog = MediaChooserConstants.getDialog(HomeFragmentActivity.this).create();
            alertDialog.show();// w  w w . java 2  s  .  co m
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    //Do something after 5000ms
                    String fileUriString = fileUri.toString().replaceFirst("file:///", "/").trim();
                    android.support.v4.app.FragmentManager fragmentManager = getSupportFragmentManager();
                    //   VideoFragment videoFragment = (VideoFragment) fragmentManager.findFragmentByTag("tab2");
                    //                  
                    //                  if(videoFragment == null){
                    //                     VideoFragment newVideoFragment = new VideoFragment();
                    //                     newVideoFragment.addItem(fileUriString);
                    //
                    //                  }else{
                    //                     videoFragment.addItem(fileUriString);
                    //                  }
                    alertDialog.cancel();
                }
            }, 5000);

        } else if (resultCode == RESULT_CANCELED) {
            // User cancelled the video capture
        } else {
            // Video capture failed, advise user
        }
    } else if (requestCode == MediaChooserConstants.CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {
        if (resultCode == RESULT_OK) {

            sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, fileUri));

            final AlertDialog alertDialog = MediaChooserConstants.getDialog(HomeFragmentActivity.this).create();
            alertDialog.show();
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    //Do something after 5000ms
                    String fileUriString = fileUri.toString().replaceFirst("file:///", "/").trim();
                    android.support.v4.app.FragmentManager fragmentManager = getSupportFragmentManager();
                    ImageFragment imageFragment = (ImageFragment) fragmentManager.findFragmentByTag("tab1");
                    if (imageFragment == null) {
                        ImageFragment newImageFragment = new ImageFragment();
                        newImageFragment.addItem(fileUriString);

                    } else {
                        imageFragment.addItem(fileUriString);
                    }
                    alertDialog.cancel();
                }
            }, 5000);
        }
    }
}

From source file:com.dycode.jepretstory.mediachooser.activity.BucketHomeFragmentActivity.java

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    super.onActivityResult(requestCode, resultCode, data);

    if (resultCode == Activity.RESULT_OK) {

        if (requestCode == MediaChooserConstants.BUCKET_SELECT_IMAGE_CODE) {
            //reset
            //addMedia(mSelectedImage, data.getStringArrayListExtra("list"));
            addMediaModel(mSelectedImages, data.getParcelableArrayListExtra("selectedImages"));

            if (mImageFragment != null) {
                mImageFragment.setCurrentSelectedImages(mSelectedImages);
            }/* w w  w  .  j  a  va2 s  . c  om*/

            onImageSelectedCount(mSelectedImages.size());

        } else if (requestCode == MediaChooserConstants.BUCKET_SELECT_VIDEO_CODE) {
            //reset
            //addMedia(mSelectedVideo, data.getStringArrayListExtra("list"));
            addMediaModel(mSelectedVideos, data.getParcelableArrayListExtra("selectedVideos"));

            if (mVideoFragment != null) {
                mVideoFragment.setCurrentSelectedVideos(mSelectedVideos);
            }

            onVideoSelectedCount(mSelectedVideos.size());

        } else if (requestCode == MediaChooserConstants.CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {

            sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, fileUri));

            final AlertDialog alertDialog = MediaChooserConstants.getDialog(BucketHomeFragmentActivity.this)
                    .create();
            alertDialog.show();

            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    // Do something after 2000ms
                    String fileUriString = fileUri.toString().replaceFirst("file:///", "/").trim();

                    if (mImageFragment != null) {
                        mImageFragment.getAdapter().addLatestEntry(fileUriString);
                        mImageFragment.getAdapter().notifyDataSetChanged();
                    }
                    alertDialog.dismiss();
                }
            }, 5000);

        } else if (requestCode == MediaChooserConstants.CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) {

            sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, fileUri));

            final AlertDialog alertDialog = MediaChooserConstants.getDialog(BucketHomeFragmentActivity.this)
                    .create();
            alertDialog.show();
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    // Do something after 2000ms
                    String fileUriString = fileUri.toString().replaceFirst("file:///", "/").trim();

                    if (mVideoFragment != null) {
                        mVideoFragment.getAdapter().addLatestEntry(fileUriString);
                        mVideoFragment.getAdapter().notifyDataSetChanged();
                    }

                    //add to mediastore
                    //addVideoToMediaStore(fileUri);

                    alertDialog.dismiss();
                }
            }, 5000);
        }
    }
}

From source file:com.vonglasow.michael.satstat.ui.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    defaultUEH = Thread.getDefaultUncaughtExceptionHandler();

    Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler() {
        public void uncaughtException(Thread t, Throwable e) {
            Context c = getApplicationContext();
            File dumpDir = c.getExternalFilesDir(null);
            DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss", Locale.ROOT);
            fmt.setTimeZone(TimeZone.getTimeZone("UTC"));
            String fileName = String.format("satstat-%s.log", fmt.format(new Date(System.currentTimeMillis())));

            File dumpFile = new File(dumpDir, fileName);
            PrintStream s;/*ww  w  .  j a  va  2 s  .  c  om*/
            try {
                InputStream buildInStream = getResources().openRawResource(R.raw.build);
                s = new PrintStream(dumpFile);
                s.append("SatStat build: ");

                int i;
                try {
                    i = buildInStream.read();
                    while (i != -1) {
                        s.write(i);
                        i = buildInStream.read();
                    }
                    buildInStream.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }

                s.append("\n\n");
                e.printStackTrace(s);
                s.flush();
                s.close();

                Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                Uri contentUri = Uri.fromFile(dumpFile);
                mediaScanIntent.setData(contentUri);
                c.sendBroadcast(mediaScanIntent);
            } catch (FileNotFoundException e2) {
                e2.printStackTrace();
            }
            defaultUEH.uncaughtException(t, e);
        }
    });

    mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
    mSharedPreferences.registerOnSharedPreferenceChangeListener(this);
    prefUnitType = mSharedPreferences.getBoolean(Const.KEY_PREF_UNIT_TYPE, prefUnitType);
    prefKnots = mSharedPreferences.getBoolean(Const.KEY_PREF_KNOTS, prefKnots);
    prefCoord = Integer
            .valueOf(mSharedPreferences.getString(Const.KEY_PREF_COORD, Integer.toString(prefCoord)));
    prefUtc = mSharedPreferences.getBoolean(Const.KEY_PREF_UTC, prefUtc);
    prefCid = mSharedPreferences.getBoolean(Const.KEY_PREF_CID, prefCid);
    prefCid2 = mSharedPreferences.getBoolean(Const.KEY_PREF_CID2, prefCid2);
    prefWifiSort = Integer
            .valueOf(mSharedPreferences.getString(Const.KEY_PREF_WIFI_SORT, Integer.toString(prefWifiSort)));
    prefMapOffline = mSharedPreferences.getBoolean(Const.KEY_PREF_MAP_OFFLINE, prefMapOffline);
    prefMapPath = mSharedPreferences.getString(Const.KEY_PREF_MAP_PATH, prefMapPath);

    ActionBar actionBar = getSupportActionBar();

    setContentView(R.layout.activity_main);

    // Find out default screen orientation
    Configuration config = getResources().getConfiguration();
    WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
    int rot = wm.getDefaultDisplay().getRotation();
    isWideScreen = (config.orientation == Configuration.ORIENTATION_LANDSCAPE
            && (rot == Surface.ROTATION_0 || rot == Surface.ROTATION_180)
            || config.orientation == Configuration.ORIENTATION_PORTRAIT
                    && (rot == Surface.ROTATION_90 || rot == Surface.ROTATION_270));
    Log.d(TAG, "isWideScreen=" + Boolean.toString(isWideScreen));

    // Create the adapter that will return a fragment for each of the
    // primary sections of the app.
    mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

    // Set up the ViewPager with the sections adapter.
    mViewPager = (ViewPager) findViewById(R.id.pager);
    mViewPager.setAdapter(mSectionsPagerAdapter);

    Context ctx = new ContextThemeWrapper(getApplication(), R.style.AppTheme);
    mTabLayout = new TabLayout(ctx);
    LinearLayout.LayoutParams mTabLayoutParams = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT,
            LayoutParams.WRAP_CONTENT);
    mTabLayout.setLayoutParams(mTabLayoutParams);

    for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
        TabLayout.Tab newTab = mTabLayout.newTab();
        newTab.setIcon(mSectionsPagerAdapter.getPageIcon(i));
        mTabLayout.addTab(newTab);
    }

    actionBar.setDisplayShowCustomEnabled(true);
    actionBar.setCustomView(mTabLayout);

    mTabLayout.setOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(mViewPager));
    mViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(mTabLayout));

    // This is needed by the mapsforge library.
    AndroidGraphicFactory.createInstance(this.getApplication());

    // Get system services for event delivery
    locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
    sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
    mOrSensor = sensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION);
    mAccSensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
    mGyroSensor = sensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE);
    mMagSensor = sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
    mLightSensor = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
    mProximitySensor = sensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY);
    mPressureSensor = sensorManager.getDefaultSensor(Sensor.TYPE_PRESSURE);
    mHumiditySensor = sensorManager.getDefaultSensor(Sensor.TYPE_RELATIVE_HUMIDITY);
    mTempSensor = sensorManager.getDefaultSensor(Sensor.TYPE_AMBIENT_TEMPERATURE);
    telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
    connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
}