Example usage for android.content Intent EXTRA_STREAM

List of usage examples for android.content Intent EXTRA_STREAM

Introduction

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

Prototype

String EXTRA_STREAM

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

Click Source Link

Document

A content: URI holding a stream of data associated with the Intent, used with #ACTION_SEND to supply the data being sent.

Usage

From source file:com.example.zayankovsky.homework.ui.ImageDetailActivity.java

@Override
public boolean onContextItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    case R.id.save:
        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[] { Manifest.permission.WRITE_EXTERNAL_STORAGE },
                    MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE);
        } else {//from  ww  w.j a v a 2s . c  o m
            saveImageToGallery();
        }
        return true;
    case R.id.browser:
        Uri webpage = Uri.parse(FotkiWorker.getUrl());
        Intent intent = new Intent(Intent.ACTION_VIEW, webpage);
        if (intent.resolveActivity(getPackageManager()) != null) {
            startActivity(intent);
            return true;
        }
        return false;
    case R.id.open:
        Uri imageUri = getUriForImage();
        if (imageUri == null) {
            return false;
        }

        Intent openIntent = new Intent();
        openIntent.setAction(Intent.ACTION_VIEW);
        // Put the Uri and MIME type in the result Intent
        openIntent.setDataAndType(imageUri, getContentResolver().getType(imageUri));
        // Grant temporary read permission to the content URI
        openIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        startActivity(openIntent);
        return true;
    case R.id.share:
        imageUri = getUriForImage();
        if (imageUri == null) {
            return false;
        }

        Intent shareIntent = new Intent();
        shareIntent.setAction(Intent.ACTION_SEND);
        // Put the Uri and MIME type in the result Intent
        shareIntent.putExtra(Intent.EXTRA_STREAM, imageUri);
        shareIntent.setType(getContentResolver().getType(imageUri));
        // Grant temporary read permission to the content URI
        shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        startActivity(Intent.createChooser(shareIntent, null));
        return true;
    default:
        return super.onContextItemSelected(item);
    }
}

From source file:com.wikonos.fingerprint.activities.MainActivity.java

/**
 * Create dialog list of logs//from   ww  w  . j  av a  2 s .co m
 * 
 * @return
 */
public AlertDialog getDialogReviewLogs() {
    /**
     * List of logs
     */
    File folder = new File(LogWriter.APPEND_PATH);
    final String[] files = folder.list(new FilenameFilter() {
        public boolean accept(File dir, String filename) {
            if (filename.contains(".log") && !filename.equals(LogWriter.DEFAULT_NAME)
                    && !filename.equals(LogWriterSensors.DEFAULT_NAME)
                    && !filename.equals(ErrorLog.DEFAULT_NAME))
                return true;
            else
                return false;
        }
    });

    Arrays.sort(files);
    ArrayUtils.reverse(files);

    String[] files_with_status = new String[files.length];
    String[] sent_mode = { "", "(s) ", "(e) ", "(s+e) " };
    for (int i = 0; i < files.length; ++i) {
        //0 -- not sent
        //1 -- server
        //2 -- email
        files_with_status[i] = sent_mode[getSentFlags(files[i], this)] + files[i];
    }

    if (files != null && files.length > 0) {

        final boolean[] selected = new boolean[files.length];

        final AlertDialog ald = new AlertDialog.Builder(MainActivity.this)
                .setMultiChoiceItems(files_with_status, selected,
                        new DialogInterface.OnMultiChoiceClickListener() {
                            public void onClick(DialogInterface dialog, int which, boolean isChecked) {
                                selected[which] = isChecked;
                            }
                        })
                .setOnCancelListener(new OnCancelListener() {
                    @Override
                    public void onCancel(DialogInterface dialog) {
                        // removeDialog(DIALOG_ID_REVIEW);
                    }
                })
                /**
                * Delete log
                */
                .setNegativeButton("Delete", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {

                        //Show delete confirm
                        standardConfirmDialog("Delete Logs", "Are you sure you want to delete selected logs?",
                                new OnClickListener() {
                                    //Confrim Delete
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {

                                        int deleteCount = 0;
                                        boolean flagSelected = false;
                                        for (int i = 0; i < selected.length; i++) {
                                            if (selected[i]) {
                                                flagSelected = true;
                                                LogWriter.delete(files[i]);
                                                LogWriter.delete(files[i].replace(".log", ".dev"));
                                                deleteCount++;
                                            }
                                        }

                                        reviewLogsCheckItems(flagSelected);

                                        removeDialog(DIALOG_ID_REVIEW);

                                        Toast.makeText(getApplicationContext(), deleteCount + " logs deleted.",
                                                Toast.LENGTH_SHORT).show();
                                    }
                                }, new OnClickListener() {
                                    //Cancel Delete
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        //Do nothing
                                        dialog.dismiss();
                                        Toast.makeText(getApplicationContext(), "Delete cancelled.",
                                                Toast.LENGTH_SHORT).show();
                                    }
                                }, false);
                    }
                })
                /**
                * Send to server functional
                **/
                .setNeutralButton("Send to Server", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        if (isOnline()) {
                            ArrayList<String> filesList = new ArrayList<String>();

                            for (int i = 0; i < selected.length; i++)
                                if (selected[i]) {

                                    filesList.add(LogWriter.APPEND_PATH + files[i]);
                                    //Move to httplogsender
                                    //setSentFlags(files[i], 1, MainActivity.this);   //Mark file as sent
                                }

                            if (reviewLogsCheckItems(filesList.size() > 0 ? true : false)) {
                                DataPersistence d = new DataPersistence(getApplicationContext());
                                new HttpLogSender(MainActivity.this,
                                        d.getServerName() + getString(R.string.submit_log_url), filesList)
                                                .setToken(getToken()).execute();
                            }

                            // removeDialog(DIALOG_ID_REVIEW);
                        } else {
                            standardAlertDialog(getString(R.string.msg_alert),
                                    getString(R.string.msg_no_internet), null);
                        }
                    }
                })
                /**
                * Email
                **/
                .setPositiveButton("eMail", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        boolean flagSelected = false;
                        // convert from paths to Android friendly
                        // Parcelable Uri's
                        ArrayList<Uri> uris = new ArrayList<Uri>();
                        for (int i = 0; i < selected.length; i++)
                            if (selected[i]) {
                                flagSelected = true;
                                /** wifi **/
                                File fileIn = new File(LogWriter.APPEND_PATH + files[i]);
                                Uri u = Uri.fromFile(fileIn);
                                uris.add(u);

                                /** sensors **/
                                File fileInSensors = new File(
                                        LogWriter.APPEND_PATH + files[i].replace(".log", ".dev"));
                                Uri uSens = Uri.fromFile(fileInSensors);
                                uris.add(uSens);

                                setSentFlags(files[i], 2, MainActivity.this); //Mark file as emailed
                            }

                        if (reviewLogsCheckItems(flagSelected)) {
                            /**
                             * Run sending email activity
                             */
                            Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND_MULTIPLE);
                            emailIntent.setType("plain/text");
                            emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT,
                                    "Wifi Searcher Scan Log");
                            emailIntent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris);
                            startActivity(Intent.createChooser(emailIntent, "Send mail..."));
                        }

                        // removeDialog(DIALOG_ID_REVIEW);
                    }
                }).create();

        ald.getListView().setOnItemLongClickListener(new OnItemLongClickListener() {

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

                AlertDialog segmentNameAlert = segmentNameDailog("Rename Segment", ald.getContext(),
                        files[position], null, view, files, position);
                segmentNameAlert.setCanceledOnTouchOutside(false);
                segmentNameAlert.show();
                return false;
            }
        });
        return ald;
    } else {
        return standardAlertDialog(getString(R.string.msg_alert), getString(R.string.msg_log_nocount),
                new OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        removeDialog(DIALOG_ID_REVIEW);
                    }
                });
    }
}

From source file:com.popdeem.sdk.core.utils.PDSocialUtils.java

/**
 * Create a chooser Intent for sharing an Image file to Instagram
 *
 * @param path Path to Image file/*from ww  w  .  jav  a 2 s.  c om*/
 * @return Chooser Intent
 */
public static Intent createInstagramIntent(Context context, String path) {
    File file = new File(path);
    Intent intent = new Intent(Intent.ACTION_SEND);
    intent.setType("image/*");
    intent.setPackage("com.instagram.android");
    Log.i("PROVIDER", "createInstagramIntent: ");
    Uri sharedFileUri = FileProvider.getUriForFile(context,
            context.getApplicationContext().getPackageName() + ".fileprovider", file);

    intent.putExtra(Intent.EXTRA_STREAM, sharedFileUri);
    return intent;
    //        return Intent.createChooser(intent, "Share to");
}

From source file:com.pixelpixel.pyp.MainActivity.java

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);/* w w  w  . j  av  a  2s .  c  o  m*/

    //We get the ImageView, and using the intent extra information
    //which contains the picture taken with the camera or
    //the picture picked from the gallery, we set the image for the ImageView.
    img = (ImageView) findViewById(R.id.main_picture);
    Bundle extras = getIntent().getExtras();
    if (extras != null) {
        //We have picture taken with the camera
        if (extras.containsKey("cPic")) {
            Uri picUri = (Uri) extras.get("cPic");
            img.setImageURI(picUri);
            getIntent().removeExtra("cPic");
            //We have picture picked from gallery
        } else if (extras.containsKey("gPic")) {
            Uri gPicUri = (Uri) extras.get("gPic");
            img.setImageURI(gPicUri);
            //Next line removes the extra information from the intent (the URI)
            getIntent().removeExtra("gPic");
        }
        //Storing the original picture
        Drawable drawing = img.getDrawable();
        picture = ((BitmapDrawable) drawing).getBitmap();
    }

    //Get the cached bitmaps
    if (mMemoryCache.get("current") != null) {
        rBitmap = (Bitmap) mMemoryCache.get("current");
        img.setImageBitmap(rBitmap);
    }
    if (mMemoryCache.get("original") != null) {
        picture = (Bitmap) mMemoryCache.get("original");
    }
    mMemoryCache.evictAll();

    //rBitmap - current bitmap on the imageView
    Log.i("TAG", "Image Displayed");
    Drawable drawing = img.getDrawable();
    rBitmap = ((BitmapDrawable) drawing).getBitmap();

    //Implementing the onClickListeners for the buttons:
    //First we get the ImageButtons
    backButton = (ImageButton) findViewById(R.id.MainImageButtonBack);
    effectsButton = (ImageButton) findViewById(R.id.MainImageButtonEffects);
    extrasButton = (ImageButton) findViewById(R.id.MainImageButtonExtras);
    saveButton = (ImageButton) findViewById(R.id.MainImageButtonSave);
    shareButton = (ImageButton) findViewById(R.id.MainImageButtonShare);

    Log.i("TAG", "Buttons recognized");

    //Defining listener for the popup menu
    //POPUP MENU IS NOT WORKING ON MINSDK=8!
    /*  PopupMenuListener = new PopupMenu.OnMenuItemClickListener() {
               
       @Override
       public boolean onMenuItemClick(MenuItem item) {
    int menuItemId = item.getItemId();      
    if (menuItemId == R.id.MenuGrayScale) {
       Log.i("TAG", "Button GrayScale indentified");
       applyGrayscaleEffect();
    }else if (menuItemId == R.id.MenuSepia) {
       Log.i("TAG", "Button Sepia identified");
       applySepiaEffect();
    }else if (menuItemId == R.id.MenuOriginal) {
       applyOriginal();
    }else if (menuItemId == R.id.MenuInverse) {
       applyInverseEffect();
    }
    return true;
       }
    };*/

    //Defining listener for ImageButtons
    View.OnClickListener ButtonListener = new View.OnClickListener() {

        public void onClick(View v) {
            ImageButton button = (ImageButton) v;
            //If we click on the back button
            if (button == backButton) {
                // A new alert dialog is created
                AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                builder.setMessage("Are you sure you want to exit?\nAll your changes will be lost.")
                        .setCancelable(false).setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                            //If we click Yes, the current activity is finished,
                            //and we return to the previous activity.
                            public void onClick(DialogInterface dialog, int which) {
                                mMemoryCache.evictAll();
                                MainActivity.this.finish();
                            }
                        }).setNegativeButton("No", new DialogInterface.OnClickListener() {
                            //If we click No, we return to the current activity
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.cancel();
                            }
                        });
                AlertDialog alert = builder.create();
                alert.show();
            } else if (button == effectsButton) {
                startActivity(new Intent(MainActivity.this, ListActivity.class));
                /*PopupMenu popup = new PopupMenu(MainActivity.this, v);
                 MenuInflater inflater = popup.getMenuInflater();
                 inflater.inflate(R.menu.effects, popup.getMenu());
                 popup.setOnMenuItemClickListener(PopupMenuListener);
                 popup.show();*/
            } else if (button == extrasButton) {
                //TODO: implement this function
            } else if (button == saveButton) {
                // A new alert dialog is created
                AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                builder.setMessage("Do you want to save your picture?").setCancelable(false)
                        .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                            //If we click Yes, picture is saved to gallery/Pimped Pictures
                            public void onClick(DialogInterface dialog, int which) {
                                try {
                                    saveFile();
                                } catch (IOException e) {

                                    e.printStackTrace();
                                }
                            }
                        }).setNegativeButton("No", new DialogInterface.OnClickListener() {
                            //If we click No, we return to the current activity
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.cancel();
                            }
                        });
                AlertDialog alert = builder.create();
                alert.show();
            } else if (button == shareButton) {
                try {
                    saveFile();
                } catch (IOException e) {

                    e.printStackTrace();
                }

                Intent share = new Intent(Intent.ACTION_SEND);
                share.setType("image/*");
                share.putExtra(Intent.EXTRA_STREAM, picUri);
                share.putExtra(Intent.EXTRA_TEXT, "Pyp test");
                startActivity(Intent.createChooser(share, "Share image"));
            }
        }
    };
    backButton.setOnClickListener(ButtonListener);
    effectsButton.setOnClickListener(ButtonListener);
    extrasButton.setOnClickListener(ButtonListener);
    saveButton.setOnClickListener(ButtonListener);
    shareButton.setOnClickListener(ButtonListener);
}

From source file:com.actionbarsherlock.sample.hcgallery.ContentFragment.java

void shareCurrentPhoto() {
    File externalCacheDir = getActivity().getExternalCacheDir();
    if (externalCacheDir == null) {
        Toast.makeText(getActivity(), "Error writing to USB/external storage.", Toast.LENGTH_SHORT).show();
        return;/*from   w  w  w . j  a v a 2  s .c  o m*/
    }

    // Prevent media scanning of the cache directory.
    final File noMediaFile = new File(externalCacheDir, ".nomedia");
    try {
        noMediaFile.createNewFile();
    } catch (IOException e) {
    }

    // Write the bitmap to temporary storage in the external storage directory (e.g. SD card).
    // We perform the actual disk write operations on a separate thread using the
    // {@link AsyncTask} class, thus avoiding the possibility of stalling the main (UI) thread.

    final File tempFile = new File(externalCacheDir, "tempfile.jpg");

    new AsyncTask<Void, Void, Boolean>() {
        /**
         * Compress and write the bitmap to disk on a separate thread.
         * @return TRUE if the write was successful, FALSE otherwise.
         */
        protected Boolean doInBackground(Void... voids) {
            try {
                FileOutputStream fo = new FileOutputStream(tempFile, false);
                if (!mBitmap.compress(Bitmap.CompressFormat.JPEG, 60, fo)) {
                    Toast.makeText(getActivity(), "Error writing bitmap data.", Toast.LENGTH_SHORT).show();
                    return Boolean.FALSE;
                }
                return Boolean.TRUE;

            } catch (FileNotFoundException e) {
                Toast.makeText(getActivity(), "Error writing to USB/external storage.", Toast.LENGTH_SHORT)
                        .show();
                return Boolean.FALSE;
            }
        }

        /**
         * After doInBackground completes (either successfully or in failure), we invoke an
         * intent to share the photo. This code is run on the main (UI) thread.
         */
        protected void onPostExecute(Boolean result) {
            if (result != Boolean.TRUE) {
                return;
            }

            Intent shareIntent = new Intent(Intent.ACTION_SEND);
            shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(tempFile));
            shareIntent.setType("image/jpeg");
            startActivity(Intent.createChooser(shareIntent, "Share photo"));
        }
    }.execute();
}

From source file:com.krayzk9s.imgurholo.activities.MainActivity.java

private void processIntent(Intent intent) {
    String action = intent.getAction();
    String type = intent.getType();
    Log.d("New Intent", intent.toString());
    if (Intent.ACTION_SEND.equals(action) && type != null) {
        if (type.startsWith("image/")) {
            Toast.makeText(this, R.string.toast_uploading, Toast.LENGTH_SHORT).show();
            Intent serviceIntent = new Intent(this, UploadService.class);
            if (intent.getExtras() == null)
                finish();//from www.ja  v  a  2 s .  c  om
            serviceIntent.setData((Uri) intent.getExtras().get("android.intent.extra.STREAM"));
            startService(serviceIntent);
            finish();
        }
    } else if (Intent.ACTION_SEND_MULTIPLE.equals(action)) {
        Log.d("sending", "sending multiple");
        Toast.makeText(this, R.string.toast_uploading, Toast.LENGTH_SHORT).show();
        ArrayList<Parcelable> list = intent.getParcelableArrayListExtra(Intent.EXTRA_STREAM);
        Intent serviceIntent = new Intent(this, UploadService.class);
        serviceIntent.putParcelableArrayListExtra("images", list);
        startService(serviceIntent);
        finish();
    } else if (Intent.ACTION_VIEW.equals(action) && intent.getData().toString().startsWith("imgur-holo")) {
        Uri uri = intent.getData();
        Log.d("URI", "" + action + "/" + type);
        String uripath = "";
        if (uri != null)
            uripath = uri.toString();
        Log.d("URI", uripath);
        Log.d("URI", "HERE");

        if (uri != null && uripath.startsWith(ApiCall.OAUTH_CALLBACK_URL)) {
            apiCall.verifier = new Verifier(uri.getQueryParameter("code"));
            CallbackAsync callbackAsync = new CallbackAsync(apiCall, this);
            callbackAsync.execute();
        }
    } else if (getSupportFragmentManager().getFragments() == null) {
        loadDefaultPage();
    }
}

From source file:eu.intermodalics.tango_ros_streamer.RunningActivity.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    case R.id.settings:
        Intent settingsActivityIntent = new Intent(this, SettingsActivity.class);
        startActivityForResult(settingsActivityIntent, startSettingsActivityRequest.STANDARD_RUN);
        return true;
    case R.id.drawer:
        if (mDrawerLayout.isDrawerOpen(Gravity.RIGHT)) {
            mDrawerLayout.closeDrawer(Gravity.RIGHT);
        } else {/*from w  w w .  j av  a 2  s.  c  o  m*/
            mDrawerLayout.openDrawer(Gravity.RIGHT);
        }
        return true;
    case R.id.share:
        mLogger.saveLogToFile();
        Intent shareFileIntent = new Intent(Intent.ACTION_SEND);
        shareFileIntent.setType("text/plain");
        shareFileIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(mLogger.getLogFile()));
        startActivity(shareFileIntent);
        return true;
    default:
        return super.onOptionsItemSelected(item);
    }
}

From source file:org.alfresco.mobile.android.application.manager.ActionManager.java

public static Intent createSendIntent(Activity activity, File contentFile) {
    Intent i = new Intent(Intent.ACTION_SEND);
    i.putExtra(Intent.EXTRA_SUBJECT, contentFile.getName());
    i.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(contentFile));
    i.setType(MimeTypeManager.getMIMEType(activity, contentFile.getName()));
    return i;// w  w  w .  ja v a  2  s.  c o  m
}

From source file:fr.simon.marquis.secretcodes.ui.MainActivity.java

private void sendEmail(ArrayList<SecretCode> secretCodes) {
    Intent i = new Intent(Intent.ACTION_SEND);
    i.setType("message/rfc822");
    i.putExtra(Intent.EXTRA_EMAIL, new String[] { getString(R.string.extra_email) });
    i.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.extra_subject));
    i.putExtra(Intent.EXTRA_TEXT, generateEmailBody(secretCodes));
    i.putExtra(Intent.EXTRA_STREAM, ExportContentProvider.CONTENT_URI);
    startActivity(Intent.createChooser(i, null));
}

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

/**
 * Open a View intent for given file/* ww w  .j ava 2  s.c o  m*/
 *
 * @param file The file to share
 */
public boolean viewFileInOtherApp(File file, @Nullable String type) {
    // On some specific devices the first won't work
    Uri fileUri = null;
    try {
        fileUri = FileProvider.getUriForFile(_context, getFileProviderAuthority(), file);
    } catch (Exception ignored) {
        try {
            fileUri = Uri.fromFile(file);
        } catch (Exception ignored2) {
        }
    }

    if (fileUri != null) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.putExtra(Intent.EXTRA_STREAM, fileUri);
        intent.setData(fileUri);
        intent.putExtra(EXTRA_FILEPATH, file.getAbsolutePath());
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        intent.setDataAndType(fileUri, type);
        showChooser(intent, null);
        return true;
    }
    return false;
}