Example usage for android.app Activity sendBroadcast

List of usage examples for android.app Activity sendBroadcast

Introduction

In this page you can find the example usage for android.app Activity sendBroadcast.

Prototype

@Override
    public void sendBroadcast(Intent intent) 

Source Link

Usage

From source file:ch.uzh.supersede.feedbacklibrary.utils.Utils.java

@NonNull
private static String captureScreenshot(final Activity activity) {
    // Create the 'Screenshots' folder if it does not already exist
    File screenshotDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
            SCREENSHOTS_DIR_NAME);//from  ww  w  . j  a  v  a2 s. com
    screenshotDir.mkdirs();

    // Image name 'Screenshot_YearMonthDay-HourMinuteSecondMillisecond.png'
    Calendar calendar = Calendar.getInstance();
    calendar.setTimeInMillis(System.currentTimeMillis());
    String imageName = "Screenshot_" + calendar.get(Calendar.YEAR) + (calendar.get(Calendar.MONTH) + 1)
            + calendar.get(Calendar.DAY_OF_MONTH);
    imageName += "-" + calendar.get(Calendar.HOUR_OF_DAY) + calendar.get(Calendar.MINUTE)
            + calendar.get(Calendar.SECOND) + calendar.get(Calendar.MILLISECOND) + ".png";
    File screenshotFile = new File(screenshotDir, imageName);

    // Create the screenshot file
    try {
        if (screenshotFile.exists()) {
            screenshotFile.delete();
        }
        screenshotFile.createNewFile();
    } catch (IOException e) {
        Log.e(TAG, "Failed to create a new file", e);
    }

    // Capture the current screen
    View rootView = activity.getWindow().getDecorView().getRootView();
    rootView.setDrawingCacheEnabled(true);
    Bitmap imageBitmap = Bitmap.createBitmap(rootView.getDrawingCache());
    rootView.setDrawingCacheEnabled(false);

    FileOutputStream fos;
    try {
        fos = new FileOutputStream(screenshotFile);
        imageBitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
        fos.flush();
        fos.close();
    } catch (Exception e) {
        Log.e(TAG, "Failed to write the bitmap to the file", e);
    }

    // Add the screenshot image to the Media Provider's database
    Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
    Uri contentUri = Uri.fromFile(screenshotFile);
    mediaScanIntent.setData(contentUri);
    activity.sendBroadcast(mediaScanIntent);

    return screenshotFile.getAbsolutePath();
}

From source file:com.saulcintero.moveon.fragments.History.java

public static void sendAction(final Activity act, int[] idList, String[] nameList, String[] activityList,
        String[] shortDescriptionList, String[] longDescriptionList) {
    ArrayList<Integer> positions = new ArrayList<Integer>();
    for (int p = 0; p < idList.length; p++) {
        String nameToSearch = osmFilesNameFromUploadPosition.get(p).substring(0,
                osmFilesNameFromUploadPosition.get(p).length() - 4);
        positions.add(ArrayUtils.indexOf(listOfFiles, nameToSearch));
    }//from  w w  w. j a  v a  2 s .c  o m

    for (int j = 0; j < idList.length; j++) {
        final String name = nameList[j];
        final String activity = activityList[j];
        final String shortDescription = shortDescriptionList[j];
        final String longDescription = longDescriptionList[j];
        final String url = osmUrlsToShare.get(positions.get(j));
        Intent sendIntent = new Intent(android.content.Intent.ACTION_SEND);
        sendIntent.setType("text/plain");
        List<ResolveInfo> activities = act.getPackageManager().queryIntentActivities(sendIntent, 0);
        AlertDialog.Builder builder = new AlertDialog.Builder(act);
        builder.setTitle(act.getText(R.string.send_to) + " " + name + " " + act.getText(R.string.share_with));
        final ShareIntentListAdapter adapter = new ShareIntentListAdapter(act, R.layout.social_share,
                activities.toArray());
        builder.setAdapter(adapter, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                ResolveInfo info = (ResolveInfo) adapter.getItem(which);
                if (info.activityInfo.packageName.contains("facebook")) {
                    Intent i = new Intent("android.intent.action.PUBLISH_TO_FB_WALL");
                    i.putExtra("name", activity + " " + name);
                    i.putExtra("msg", String.format("%s", shortDescription));
                    i.putExtra("link", String.format("%s", url));
                    act.sendBroadcast(i);
                } else {
                    Intent intent = new Intent(android.content.Intent.ACTION_SEND);
                    intent.setClassName(info.activityInfo.packageName, info.activityInfo.name);
                    intent.setType("text/plain");
                    if ((info.activityInfo.packageName.contains("twitter"))
                            || (info.activityInfo.packageName.contains("sms"))
                            || (info.activityInfo.packageName.contains("mms"))) {
                        intent.putExtra(Intent.EXTRA_TEXT, shortDescription + url);
                    } else {
                        intent.putExtra(Intent.EXTRA_TEXT, longDescription + url);
                    }
                    act.startActivity(intent);
                }
            }
        });
        builder.create().show();
    }
}

From source file:org.catrobat.catroid.ui.controller.LookController.java

private void copyImageToCatroid(String originalImagePath, Activity activity, ArrayList<LookData> lookDataList,
        LookFragment fragment) {/*  w  ww  . jav a 2 s.  c o m*/
    try {

        int[] imageDimensions = ImageEditing.getImageDimensions(originalImagePath);

        if (imageDimensions[0] < 0 || imageDimensions[1] < 0) {
            Utils.showErrorDialog(activity, R.string.error_load_image);
            return;
        }

        File oldFile = new File(originalImagePath);

        if (originalImagePath.equals("")) {
            throw new IOException();
        }

        String projectName = ProjectManager.getInstance().getCurrentProject().getName();
        File imageFile = StorageHandler.getInstance().copyImage(projectName, originalImagePath, null);

        String imageName;
        int extensionDotIndex = oldFile.getName().lastIndexOf('.');
        if (extensionDotIndex > 0) {
            imageName = oldFile.getName().substring(0, extensionDotIndex);
        } else {
            imageName = oldFile.getName();
        }

        String imageFileName = imageFile.getName();
        // if pixmap cannot be created, image would throw an Exception in stage
        // so has to be loaded again with other Config
        Pixmap pixmap = null;
        pixmap = Utils.getPixmapFromFile(imageFile);

        if (pixmap == null) {
            ImageEditing.overwriteImageFileWithNewBitmap(imageFile);
            pixmap = Utils.getPixmapFromFile(imageFile);

            if (pixmap == null) {
                Utils.showErrorDialog(activity, R.string.error_load_image);
                StorageHandler.getInstance().deleteFile(imageFile.getAbsolutePath());
                return;
            }
        }
        pixmap = null;
        updateLookAdapter(imageName, imageFileName, lookDataList, fragment);
    } catch (IOException e) {
        Utils.showErrorDialog(activity, R.string.error_load_image);
    } catch (NullPointerException e) {
        Log.e("NullPointerException", "probably originalImagePath null; message: " + e.getMessage());
        Utils.showErrorDialog(activity, R.string.error_load_image);
    }
    fragment.destroyLoader();
    activity.sendBroadcast(new Intent(ScriptActivity.ACTION_BRICK_LIST_CHANGED));
}

From source file:hku.fyp14017.blencode.ui.controller.LookController.java

private void copyImageToCatroid(String originalImagePath, Activity activity, ArrayList<LookData> lookDataList,
        LookFragment fragment) {//from  ww w.  j  av a 2 s  .  co  m
    try {

        int[] imageDimensions = ImageEditing.getImageDimensions(originalImagePath);

        if (imageDimensions[0] < 0 || imageDimensions[1] < 0) {
            Utils.showErrorDialog(activity, hku.fyp14017.blencode.R.string.error_load_image);
            return;
        }

        File oldFile = new File(originalImagePath);

        if (originalImagePath.equals("")) {
            throw new IOException();
        }

        String projectName = ProjectManager.getInstance().getCurrentProject().getName();
        File imageFile = StorageHandler.getInstance().copyImage(projectName, originalImagePath, null);

        String imageName;
        int extensionDotIndex = oldFile.getName().lastIndexOf('.');
        if (extensionDotIndex > 0) {
            imageName = oldFile.getName().substring(0, extensionDotIndex);
        } else {
            imageName = oldFile.getName();
        }

        String imageFileName = imageFile.getName();
        // if pixmap cannot be created, image would throw an Exception in stage
        // so has to be loaded again with other Config
        Pixmap pixmap = null;
        pixmap = Utils.getPixmapFromFile(imageFile);

        if (pixmap == null) {
            ImageEditing.overwriteImageFileWithNewBitmap(imageFile);
            pixmap = Utils.getPixmapFromFile(imageFile);

            if (pixmap == null) {
                Utils.showErrorDialog(activity, hku.fyp14017.blencode.R.string.error_load_image);
                StorageHandler.getInstance().deleteFile(imageFile.getAbsolutePath());
                return;
            }
        }
        pixmap = null;
        updateLookAdapter(imageName, imageFileName, lookDataList, fragment);
    } catch (IOException e) {
        Utils.showErrorDialog(activity, hku.fyp14017.blencode.R.string.error_load_image);
    } catch (NullPointerException e) {
        Log.e("NullPointerException", "probably originalImagePath null; message: " + e.getMessage());
        Utils.showErrorDialog(activity, hku.fyp14017.blencode.R.string.error_load_image);
    }
    fragment.destroyLoader();
    activity.sendBroadcast(new Intent(ScriptActivity.ACTION_BRICK_LIST_CHANGED));
}

From source file:org.quantumbadger.redreader.reddit.prepared.RedditPreparedPost.java

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

    switch (action) {

    case UPVOTE:// w ww . j a  v a 2s  .  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 DELETE:
        new AlertDialog.Builder(activity).setTitle(R.string.accounts_delete).setMessage(R.string.delete_confirm)
                .setPositiveButton(R.string.action_delete, new DialogInterface.OnClickListener() {
                    public void onClick(final DialogInterface dialog, final int which) {
                        post.action(activity, RedditAPI.RedditAction.DELETE);
                    }
                }).setNegativeButton(R.string.dialog_cancel, null).show();
        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();

        LinkHandler.getImageInfo(activity, post.url, Constants.Priority.IMAGE_VIEW, 0,
                new GetImageInfoListener() {

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

                    @Override
                    public void onSuccess(final ImgurAPI.ImageInfo info) {

                        CacheManager.getInstance(activity)
                                .makeRequest(new CacheRequest(General.uriFromString(info.urlOriginal), 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(boolean authorizationInProgress, 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(info.urlOriginal).getPath());

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

                                            while (dst.exists()) {
                                                count++;
                                                dst = new File(
                                                        Environment.getExternalStoragePublicDirectory(
                                                                Environment.DIRECTORY_PICTURES),
                                                        count + "_" + General.uriFromString(info.urlOriginal)
                                                                .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());
                                    }
                                });

                    }

                    @Override
                    public void onNotAnImage() {
                        General.quickToast(activity, R.string.selected_link_is_not_image);
                    }
                });

        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.getFragmentManager(), null);
        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;
    }
}