Example usage for android.content Intent setType

List of usage examples for android.content Intent setType

Introduction

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

Prototype

public @NonNull Intent setType(@Nullable String type) 

Source Link

Document

Set an explicit MIME data type.

Usage

From source file:net.bluecarrot.lite.MainActivity.java

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

    // setup the sharedPreferences
    savedPreferences = PreferenceManager.getDefaultSharedPreferences(this);

    // if the app is being launched for the first time
    if (savedPreferences.getBoolean("first_run", true)) {
        //todo presentation
        // save the fact that the app has been started at least once
        savedPreferences.edit().putBoolean("first_run", false).apply();
    }/*from w w w.  j ava  2  s  . c o  m*/

    setContentView(R.layout.activity_main);//load the layout

    //**MOBFOX***//

    banner = (Banner) findViewById(R.id.banner);
    final Activity self = this;

    banner.setListener(new BannerListener() {
        @Override
        public void onBannerError(View view, Exception e) {
            //Toast.makeText(self, e.getMessage(), Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onBannerLoaded(View view) {
            //Toast.makeText(self, "banner loaded", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onBannerClosed(View view) {
            //Toast.makeText(self, "banner closed", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onBannerFinished(View view) {
            // Toast.makeText(self, "banner finished", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onBannerClicked(View view) {
            //Toast.makeText(self, "banner clicked", Toast.LENGTH_SHORT).show();
        }

        @Override
        public boolean onCustomEvent(JSONArray jsonArray) {
            return false;
        }
    });

    banner.setInventoryHash(appHash);
    banner.load();

    // setup the refresh layout
    swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_container);
    swipeRefreshLayout.setColorSchemeResources(R.color.officialBlueFacebook, R.color.darkBlueSlimFacebookTheme);// set the colors
    swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
        @Override
        public void onRefresh() {
            refreshPage();//reload the page
            swipeRefresh = true;
        }
    });

    /** get a subject and text and check if this is a link trying to be shared */
    String sharedSubject = getIntent().getStringExtra(Intent.EXTRA_SUBJECT);
    String sharedUrl = getIntent().getStringExtra(Intent.EXTRA_TEXT);

    // if we have a valid URL that was shared by us, open the sharer
    if (sharedUrl != null) {
        if (!sharedUrl.equals("")) {
            // check if the URL being shared is a proper web URL
            if (!sharedUrl.startsWith("http://") || !sharedUrl.startsWith("https://")) {
                // if it's not, let's see if it includes an URL in it (prefixed with a message)
                int startUrlIndex = sharedUrl.indexOf("http:");
                if (startUrlIndex > 0) {
                    // seems like it's prefixed with a message, let's trim the start and get the URL only
                    sharedUrl = sharedUrl.substring(startUrlIndex);
                }
            }
            // final step, set the proper Sharer...
            urlSharer = String.format("https://m.facebook.com/sharer.php?u=%s&t=%s", sharedUrl, sharedSubject);
            // ... and parse it just in case
            urlSharer = Uri.parse(urlSharer).toString();
            isSharer = true;
        }
    }

    // setup the webView
    webViewFacebook = (WebView) findViewById(R.id.webView);
    setUpWebViewDefaults(webViewFacebook);
    //fits images to screen

    if (isSharer) {//if is a share request
        webViewFacebook.loadUrl(urlSharer);//load the sharer url
        isSharer = false;
    } else
        goHome();//load homepage

    //        webViewFacebook.setOnTouchListener(new OnSwipeTouchListener(getApplicationContext()) {
    //            public void onSwipeLeft() {
    //                webViewFacebook.loadUrl("javascript:try{document.querySelector('#messages_jewel > a').click();}catch(e){window.location.href='" +
    //                        getString(R.string.urlFacebookMobile) + "messages/';}");
    //            }
    //
    //        });

    //WebViewClient that is the client callback.
    webViewFacebook.setWebViewClient(new WebViewClient() {//advanced set up

        // when there isn't a connetion
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            String summary = "<h1 style='text-align:center; padding-top:15%; font-size:70px;'>"
                    + getString(R.string.titleNoConnection) + "</h1> <h3 "
                    + "style='text-align:center; padding-top:1%; font-style: italic;font-size:50px;'>"
                    + getString(R.string.descriptionNoConnection)
                    + "</h3>  <h5 style='font-size:30px; text-align:center; padding-top:80%; "
                    + "opacity: 0.3;'>" + getString(R.string.awards) + "</h5>";
            webViewFacebook.loadData(summary, "text/html; charset=utf-8", "utf-8");//load a custom html page

            noConnectionError = true;
            swipeRefreshLayout.setRefreshing(false); //when the page is loaded, stop the refreshing
        }

        // when I click in a external link
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if (url == null || Uri.parse(url).getHost().endsWith("facebook.com")
                    || Uri.parse(url).getHost().endsWith("m.facebook.com") || url.contains(".gif")) {
                //url is ok
                return false;
            } else {
                if (Uri.parse(url).getHost().endsWith("fbcdn.net")) {
                    //TODO add the possibility to download and share directly

                    Toast.makeText(getApplicationContext(), getString(R.string.downloadOrShareWithBrowser),
                            Toast.LENGTH_LONG).show();
                    //TODO get bitmap from url

                    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                    startActivity(intent);
                    return true;
                }

                //if the link doesn't contain 'facebook.com', open it using the browser
                startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
                return true;
            } //https://www.facebook.com/dialog/return/close?#_=_
        }

        //START management of loading
        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            //TODO when I push on messages, open messanger
            //                if(url!=null){
            //                    if (url.contains("soft=messages") || url.contains("facebook.com/messages")) {
            //                        Toast.makeText(getApplicationContext(),"Open Messanger",
            //                                Toast.LENGTH_SHORT).show();
            //                        startActivity(new Intent(getPackageManager().getLaunchIntentForPackage("com.facebook.orca")));//messanger
            //                    }
            //                }

            // show you progress image
            if (!swipeRefresh) {
                if (optionsMenu != null) {//TODO fix this. Sometimes it is null and I don't know why
                    final MenuItem refreshItem = optionsMenu.findItem(R.id.refresh);
                    refreshItem.setActionView(R.layout.circular_progress_bar);
                }
            }
            swipeRefresh = false;
            super.onPageStarted(view, url, favicon);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            if (optionsMenu != null) {//TODO fix this. Sometimes it is null and I don't know why
                final MenuItem refreshItem = optionsMenu.findItem(R.id.refresh);
                refreshItem.setActionView(null);
            }

            //load the css customizations
            String css = "";
            if (savedPreferences.getBoolean("pref_blackTheme", false)) {
                css += getString(R.string.blackCss);
            }
            if (savedPreferences.getBoolean("pref_fixedBar", true)) {

                css += getString(R.string.fixedBar);//get the first part

                int navbar = 0;//default value
                int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");//get id
                if (resourceId > 0) {//if there is
                    navbar = getResources().getDimensionPixelSize(resourceId);//get the dimension
                }
                float density = getResources().getDisplayMetrics().density;
                int barHeight = (int) ((getResources().getDisplayMetrics().heightPixels - navbar - 44)
                        / density);

                css += ".flyout { max-height:" + barHeight + "px; overflow-y:scroll;  }";//without this doen-t scroll

            }
            if (savedPreferences.getBoolean("pref_hideSponsoredPosts", false)) {
                css += getString(R.string.hideSponsoredPost);
            }

            //apply the customizations
            webViewFacebook.loadUrl(
                    "javascript:function addStyleString(str) { var node = document.createElement('style'); node.innerHTML = "
                            + "str; document.body.appendChild(node); } addStyleString('" + css + "');");

            //finish the load
            super.onPageFinished(view, url);

            //when the page is loaded, stop the refreshing
            swipeRefreshLayout.setRefreshing(false);
        }
        //END management of loading

    });

    //WebChromeClient for handling all chrome functions.
    webViewFacebook.setWebChromeClient(new WebChromeClient() {
        //to the Geolocation
        public void onGeolocationPermissionsShowPrompt(String origin,
                GeolocationPermissions.Callback callback) {
            callback.invoke(origin, true, false);
            //todo notify when the gps is used
        }

        //to upload files
        //!!!!!!!!!!! thanks to FaceSlim !!!!!!!!!!!!!!!
        // for >= Lollipop, all in one
        public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback,
                FileChooserParams fileChooserParams) {

            /** Request permission for external storage access.
             *  If granted it's awesome and go on,
             *  otherwise just stop here and leave the method.
             */
            if (mFilePathCallback != null) {
                mFilePathCallback.onReceiveValue(null);
            }
            mFilePathCallback = filePathCallback;

            Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            if (takePictureIntent.resolveActivity(getPackageManager()) != null) {

                // create the file where the photo should go
                File photoFile = null;
                try {
                    photoFile = createImageFile();
                    takePictureIntent.putExtra("PhotoPath", mCameraPhotoPath);
                } catch (IOException ex) {
                    // Error occurred while creating the File
                    Toast.makeText(getApplicationContext(), "Error occurred while creating the File",
                            Toast.LENGTH_LONG).show();
                }

                // continue only if the file was successfully created
                if (photoFile != null) {
                    mCameraPhotoPath = "file:" + photoFile.getAbsolutePath();
                    takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
                } else {
                    takePictureIntent = null;
                }
            }

            Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT);
            contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);
            contentSelectionIntent.setType("image/*");

            Intent[] intentArray;
            if (takePictureIntent != null) {
                intentArray = new Intent[] { takePictureIntent };
            } else {
                intentArray = new Intent[0];
            }

            Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);
            chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent);
            chooserIntent.putExtra(Intent.EXTRA_TITLE, getString(R.string.chooseAnImage));
            chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray);

            startActivityForResult(chooserIntent, FILECHOOSER_RESULTCODE);

            return true;
        }

        // creating image files (Lollipop only)
        private File createImageFile() throws IOException {
            String appDirectoryName = getString(R.string.app_name).replace(" ", "");
            File imageStorageDir = new File(
                    Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
                    appDirectoryName);

            if (!imageStorageDir.exists()) {
                //noinspection ResultOfMethodCallIgnored
                imageStorageDir.mkdirs();
            }

            // create an image file name
            imageStorageDir = new File(imageStorageDir + File.separator + "IMG_"
                    + String.valueOf(System.currentTimeMillis()) + ".jpg");
            return imageStorageDir;
        }

        // openFileChooser for Android 3.0+
        public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
            String appDirectoryName = getString(R.string.app_name).replace(" ", "");
            mUploadMessage = uploadMsg;

            try {
                File imageStorageDir = new File(
                        Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
                        appDirectoryName);

                if (!imageStorageDir.exists()) {
                    //noinspection ResultOfMethodCallIgnored
                    imageStorageDir.mkdirs();
                }

                File file = new File(imageStorageDir + File.separator + "IMG_"
                        + String.valueOf(System.currentTimeMillis()) + ".jpg");

                mCapturedImageURI = Uri.fromFile(file); // save to the private variable

                final Intent captureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, mCapturedImageURI);
                //captureIntent.putExtra(MediaStore.EXTRA_SCREEN_ORIENTATION, ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

                Intent i = new Intent(Intent.ACTION_GET_CONTENT);
                i.addCategory(Intent.CATEGORY_OPENABLE);
                i.setType("image/*");

                Intent chooserIntent = Intent.createChooser(i, getString(R.string.chooseAnImage));
                chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Parcelable[] { captureIntent });

                startActivityForResult(chooserIntent, FILECHOOSER_RESULTCODE);
            } catch (Exception e) {
                Toast.makeText(getApplicationContext(), ("Camera Exception"), Toast.LENGTH_LONG).show();
            }
        }

        // openFileChooser for other Android versions

        /**
         * may not work on KitKat due to lack of implementation of openFileChooser() or onShowFileChooser()
         * https://code.google.com/p/android/issues/detail?id=62220
         * however newer versions of KitKat fixed it on some devices
         */
        public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
            openFileChooser(uploadMsg, acceptType);
        }

    });

    // OnLongClickListener for detecting long clicks on links and images
    // !!!!!!!!!!! thanks to FaceSlim !!!!!!!!!!!!!!!
    webViewFacebook.setOnLongClickListener(new View.OnLongClickListener() {
        @Override
        public boolean onLongClick(View v) {
            // activate long clicks on links and image links according to settings
            if (true) {
                WebView.HitTestResult result = webViewFacebook.getHitTestResult();
                if (result.getType() == WebView.HitTestResult.SRC_ANCHOR_TYPE
                        || result.getType() == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE) {
                    Message msg = linkHandler.obtainMessage();
                    webViewFacebook.requestFocusNodeHref(msg);
                    return true;
                }
            }
            return false;
        }
    });
    // ATTENTION: This was auto-generated to implement the App Indexing API.
    // See https://g.co/AppIndexing/AndroidStudio for more information.
    client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}

From source file:com.flipzu.flipzu.Player.java

private void share() {

    if (mUser == null || bcast == null)
        return;//from  w w  w . jav  a2  s.  c  om

    //create the intent  
    Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);

    //set the type  
    shareIntent.setType("text/plain");

    //add a subject  
    shareIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, mUser.getFullname() + " live on FlipZu");

    String text = bcast.getText();
    if (text == null) {
        text = mUser.getUsername() + " live on FlipZu";
    }

    //build the body of the message to be shared  
    String shareMessage = text + " - http://fzu.fm/" + bcast.getId();

    //add the message  
    shareIntent.putExtra(android.content.Intent.EXTRA_TEXT, shareMessage);

    //start the chooser for sharing  
    startActivity(Intent.createChooser(shareIntent, getText(R.string.share_bcast_with)));

}

From source file:com.ccxt.whl.activity.SettingsFragment.java

/**
 * ?//from   w w w. j a  v a 2 s. c  om
 */
public void selectPicFromLocal() {
    Intent intent;
    if (Build.VERSION.SDK_INT < 19) {
        intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("image/*");

        //Intent intent = new Intent(Intent.ACTION_GET_CONTENT, null); 
        /*intent.setType("image/*"); 
        intent.putExtra("crop", "true"); 
        intent.putExtra("aspectX", 1); 
        intent.putExtra("aspectY", 1); 
        intent.putExtra("outputX", 600); 
        intent.putExtra("outputY", 600); 
        intent.putExtra("scale", true); 
        intent.putExtra("return-data", false);  
        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUritest); 
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString()); 
        intent.putExtra("noFaceDetection", true); // no face detection 
         */
        //startActivityForResult(intent, CHOOSE_BIG_PICTURE); 
    } else {
        intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        //startActivityForResult(intent, USERPIC_REQUEST_CODE_LOCAL_19);
    }
    startActivityForResult(intent, USERPIC_REQUEST_CODE_LOCAL);
}

From source file:com.phonegap.plugins.wsiCameraLauncher.WsiCameraLauncher.java

/**
 * Get image from photo library./*from  w w w. j a  v a  2 s. c  o m*/
 * 
 * @param quality
 *            Compression quality hint (0-100: 0=low quality & high
 *            compression, 100=compress of max quality)
 * @param srcType
 *            The album to get image from.
 * @param returnType
 *            Set the type of image to return.
 */
// TODO: Images selected from SDCARD don't display correctly, but from
// CAMERA ALBUM do!
public void getImage(int srcType, int returnType) {

    final int srcTypeFinal = srcType;
    final int returnTypeFinal = returnType;

    String[] choices = { "Upload a Photo", "Upload a Video" };

    AlertDialog.Builder builder = new AlertDialog.Builder(this.cordova.getActivity());
    builder.setItems(choices, new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
            Log.d(LOG_TAG, "Index #" + which + " chosen.");
            Intent intent = new Intent();
            if (which == 0) {
                // set up photo intent
                WsiCameraLauncher.this.mediaType = PICTURE;
                intent.setType("image/*");
            } else if (which == 1) {
                // set up video intent
                WsiCameraLauncher.this.mediaType = VIDEO;
                intent.setType("video/*");
            } else {
                WsiCameraLauncher.this.failPicture("Selection cancelled.");
                return;
            }
            intent.setAction(Intent.ACTION_GET_CONTENT);
            intent.addCategory(Intent.CATEGORY_OPENABLE);
            if (WsiCameraLauncher.this.cordova != null) {
                WsiCameraLauncher.this.cordova.startActivityForResult((CordovaPlugin) WsiCameraLauncher.this,
                        Intent.createChooser(intent, new String("Pick")),
                        (srcTypeFinal + 1) * 16 + returnTypeFinal + 1);
            }
        }
    });
    builder.setOnKeyListener(new DialogInterface.OnKeyListener() {
        @Override
        public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
            if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_UP
                    && !event.isCanceled()) {
                dialog.cancel();
                WsiCameraLauncher.this.failPicture("Selection cancelled.");
                return true;
            }
            return false;
        }
    });
    builder.show();
}

From source file:com.awrtechnologies.carbudgetsales.MainActivity.java

public void imageOpen(Fragment f, final int REQUEST_CAMERA, final int SELECT_FILE) {

    GeneralHelper.getInstance(MainActivity.this).setTempFragment(f);
    final CharSequence[] items = { "Take Photo", "Choose from Library", "Cancel" };

    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setTitle("Add Photo!");
    builder.setItems(items, new DialogInterface.OnClickListener() {

        @Override//from  w  w  w. jav a 2s  .co m
        public void onClick(DialogInterface dialog, int item) {
            if (items[item].equals("Take Photo")) {

                java.io.File imageFile = new File(
                        (Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM) + "/."
                                + Constants.APPNAME + "/" + System.currentTimeMillis() + ".jpeg"));

                PreferencesManager.setPreferenceByKey(MainActivity.this, "IMAGEWWC",
                        imageFile.getAbsolutePath());
                //
                imageFilePath = imageFile;
                imageFileUri = Uri.fromFile(imageFile);
                Intent i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
                i.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, imageFileUri);
                startActivityForResult(i, REQUEST_CAMERA);

            } else if (items[item].equals("Choose from Library")) {
                if (Build.VERSION.SDK_INT < 19) {
                    Intent intent = new Intent(Intent.ACTION_PICK,
                            android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                    intent.setType("image/*");
                    startActivityForResult(Intent.createChooser(intent, "Select File"), SELECT_FILE);
                } else {
                    Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
                    intent.addCategory(Intent.CATEGORY_OPENABLE);
                    intent.setType("image/*");
                    startActivityForResult(Intent.createChooser(intent, "Select File"), SELECT_FILE);
                }

            } else if (items[item].equals("Cancel")) {
                dialog.dismiss();
            }
        }
    });
    builder.show();
}

From source file:com.nttec.everychan.ui.gallery.GalleryActivity.java

private void shareLink() {
    GalleryItemViewTag tag = getCurrentTag();
    if (tag == null)
        return;//from  ww w.jav  a 2s.c  o m
    String absoluteUrl = remote.getAbsoluteUrl(tag.attachmentModel.path);
    if (absoluteUrl == null)
        return;
    Intent shareIntent = new Intent(Intent.ACTION_SEND);
    shareIntent.setType("text/plain");
    shareIntent.putExtra(Intent.EXTRA_SUBJECT, absoluteUrl);
    shareIntent.putExtra(Intent.EXTRA_TEXT, absoluteUrl);
    startActivity(Intent.createChooser(shareIntent, getString(R.string.share_via)));
}

From source file:fiskinfoo.no.sintef.fiskinfoo.MyToolsFragment.java

private void generateAndSendGeoJsonToolReport() {
    FiskInfoUtility fiskInfoUtility = new FiskInfoUtility();
    JSONObject featureCollection = new JSONObject();

    try {//from   ww  w  . ja  v a2  s. c om
        Set<Map.Entry<String, ArrayList<ToolEntry>>> tools = user.getToolLog().myLog.entrySet();
        JSONArray featureList = new JSONArray();

        for (final Map.Entry<String, ArrayList<ToolEntry>> dateEntry : tools) {
            for (final ToolEntry toolEntry : dateEntry.getValue()) {
                if (toolEntry.getToolStatus() == ToolEntryStatus.STATUS_RECEIVED
                        || toolEntry.getToolStatus() == ToolEntryStatus.STATUS_REMOVED) {
                    continue;
                }

                toolEntry.setToolStatus(toolEntry.getToolStatus() == ToolEntryStatus.STATUS_REMOVED_UNCONFIRMED
                        ? ToolEntryStatus.STATUS_REMOVED_UNCONFIRMED
                        : ToolEntryStatus.STATUS_SENT_UNCONFIRMED);
                JSONObject gjsonTool = toolEntry.toGeoJson(mGpsLocationTracker);
                featureList.put(gjsonTool);
            }
        }

        if (featureList.length() == 0) {
            Toast.makeText(getActivity(), getString(R.string.no_changes_to_report), Toast.LENGTH_LONG).show();

            return;
        }

        user.writeToSharedPref(getActivity());
        featureCollection.put("features", featureList);
        featureCollection.put("type", "FeatureCollection");
        featureCollection.put("crs", JSONObject.NULL);
        featureCollection.put("bbox", JSONObject.NULL);

        String toolString = featureCollection.toString(4);

        if (fiskInfoUtility.isExternalStorageWritable()) {
            fiskInfoUtility.writeMapLayerToExternalStorage(getActivity(), toolString.getBytes(),
                    getString(R.string.tool_report_file_name), getString(R.string.format_geojson), null, false);
            String directoryPath = Environment
                    .getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString();
            String fileName = directoryPath + "/FiskInfo/api_setting.json";
            File apiSettingsFile = new File(fileName);
            String recipient = null;

            if (apiSettingsFile.exists()) {
                InputStream inputStream;
                InputStreamReader streamReader;
                JsonReader jsonReader;

                try {
                    inputStream = new BufferedInputStream(new FileInputStream(apiSettingsFile));
                    streamReader = new InputStreamReader(inputStream, "UTF-8");
                    jsonReader = new JsonReader(streamReader);

                    jsonReader.beginObject();
                    while (jsonReader.hasNext()) {
                        String name = jsonReader.nextName();
                        if (name.equals("email")) {
                            recipient = jsonReader.nextString();
                        } else {
                            jsonReader.skipValue();
                        }
                    }
                    jsonReader.endObject();
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (IllegalStateException e) {
                    e.printStackTrace();
                }
            }

            recipient = recipient == null ? getString(R.string.tool_report_recipient_email) : recipient;
            String[] recipients = new String[] { recipient };
            Intent intent = new Intent(Intent.ACTION_SEND);
            intent.setType("plain/plain");

            String toolIds;
            StringBuilder sb = new StringBuilder();

            sb.append("Redskapskoder:\n");

            for (int i = 0; i < featureList.length(); i++) {
                sb.append(Integer.toString(i + 1));
                sb.append(": ");
                sb.append(featureList.getJSONObject(i).getJSONObject("properties").getString("ToolId"));
                sb.append("\n");
            }

            toolIds = sb.toString();

            intent.putExtra(Intent.EXTRA_EMAIL, recipients);
            intent.putExtra(Intent.EXTRA_TEXT, toolIds);
            intent.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.tool_report_email_header));
            File file = new File(
                    Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getPath()
                            + "/FiskInfo/Redskapsrapport.geojson");
            Uri uri = Uri.fromFile(file);
            intent.putExtra(Intent.EXTRA_STREAM, uri);

            startActivity(Intent.createChooser(intent, getString(R.string.send_tool_report_intent_header)));

        }
    } catch (JSONException e) {
        e.printStackTrace();
    }
}

From source file:com.hivewallet.androidclient.wallet.ui.WalletActivity.java

private boolean archiveWalletBackup(@Nonnull final File file) {
    Uri shareableUri = null;//from   w ww .  ja v a2  s  .com
    try {
        shareableUri = FileProvider.getUriForFile(this, Constants.FILE_PROVIDER_AUTHORITY, file);
    } catch (IllegalArgumentException e) {
        throw new RuntimeException("Backup file cannot be shared", e);
    }

    log.info("Shareable URI: {}", shareableUri);

    final Intent intent = new Intent(Intent.ACTION_SEND);
    intent.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.export_keys_dialog_mail_subject));
    intent.putExtra(Intent.EXTRA_TEXT,
            getString(R.string.export_keys_dialog_mail_text) + "\n\n"
                    + String.format(Constants.WEBMARKET_APP_URL, getPackageName()) + "\n\n"
                    + Constants.SOURCE_URL + '\n');
    intent.setType(Constants.MIMETYPE_WALLET_BACKUP);
    intent.putExtra(Intent.EXTRA_STREAM, shareableUri);
    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

    try {
        startActivity(Intent.createChooser(intent, getString(R.string.export_keys_dialog_mail_intent_chooser)));
        log.info("invoked chooser for archiving wallet backup");
        return true;
    } catch (final Exception x) {
        longToast(R.string.export_keys_dialog_mail_intent_failed);
        log.error("archiving wallet backup failed", x);
        return false;
    }
}

From source file:org.cryptsecure.Utility.java

/**
 * Select attachment./*from   ww w .ja v a  2 s  . co m*/
 * 
 * @param activity
 *            the activity
 */
public static void selectFromGallery(Activity activity) {
    Intent intent = new Intent();
    if (Build.VERSION.SDK_INT >= 19) {
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        activity.startActivityForResult(Intent.createChooser(intent, "Select Attachment"),
                Utility.SELECT_PICTURE);

    } else {
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_PICK);
        activity.startActivityForResult(Intent.createChooser(intent, "Select Attachment"),
                Utility.SELECT_PICTURE);
    }
}