Example usage for android.os Environment DIRECTORY_DOWNLOADS

List of usage examples for android.os Environment DIRECTORY_DOWNLOADS

Introduction

In this page you can find the example usage for android.os Environment DIRECTORY_DOWNLOADS.

Prototype

String DIRECTORY_DOWNLOADS

To view the source code for android.os Environment DIRECTORY_DOWNLOADS.

Click Source Link

Document

Standard directory in which to place files that have been downloaded by the user.

Usage

From source file:com.tct.emailcommon.utility.AttachmentUtilities.java

/**
 * Save the attachment to its final resting place (cache or sd card)
 */// w w w  .j av  a  2 s. com
public static long saveAttachment(Context context, InputStream in, Attachment attachment) {
    final Uri uri = ContentUris.withAppendedId(Attachment.CONTENT_URI, attachment.mId);
    final ContentValues cv = new ContentValues();
    final long attachmentId = attachment.mId;
    final long accountId = attachment.mAccountKey;
    //TS: wenggangjin 2014-12-11 EMAIL BUGFIX_868520 MOD_S
    String contentUri = null;
    //TS: wenggangjin 2014-12-11 EMAIL BUGFIX_868520 MOD_E
    String realUri = null; //TS: zheng.zou 2016-1-22 EMAIL BUGFIX-1431088 ADD
    long size = 0;

    try {
        ContentResolver resolver = context.getContentResolver();
        if (attachment.mUiDestination == UIProvider.UIPROVIDER_ATTACHMENTDESTINATION_CACHE) {
            LogUtils.i(LogUtils.TAG, "AttachmentUtilities saveAttachment when attachment destination is cache",
                    "attachment.size:" + attachment.mSize);
            Uri attUri = getAttachmentUri(accountId, attachmentId);
            size = copyFile(in, resolver.openOutputStream(attUri));
            contentUri = attUri.toString();
        } else if (Utility.isExternalStorageMounted()) {
            LogUtils.i(LogUtils.TAG, "AttachmentUtilities saveAttachment to storage",
                    "attachment.size:" + attachment.mSize);
            if (TextUtils.isEmpty(attachment.mFileName)) {
                // TODO: This will prevent a crash but does not surface the underlying problem
                // to the user correctly.
                LogUtils.w(Logging.LOG_TAG, "Trying to save an attachment with no name: %d", attachmentId);
                throw new IOException("Can't save an attachment with no name");
            }
            //TS: zheng.zou 2016-1-22 EMAIL BUGFIX-1431088 ADD_S
            String exchange = "com.tct.exchange";
            if (exchange.equals(context.getPackageName()) && !PermissionUtil
                    .checkPermissionAndLaunchExplain(context, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                throw new IOException("Can't save an attachment due to no Storage permission");
            }
            //TS: zheng.zou 2016-1-22 EMAIL BUGFIX-1431088 ADD_E
            File downloads = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
            downloads.mkdirs();
            File file = Utility.createUniqueFile(downloads, attachment.mFileName);
            size = copyFile(in, new FileOutputStream(file));
            String absolutePath = file.getAbsolutePath();
            realUri = "file://" + absolutePath; //TS: zheng.zou 2016-1-22 EMAIL BUGFIX-1431088 ADD

            // Although the download manager can scan media files, scanning only happens
            // after the user clicks on the item in the Downloads app. So, we run the
            // attachment through the media scanner ourselves so it gets added to
            // gallery / music immediately.
            MediaScannerConnection.scanFile(context, new String[] { absolutePath }, null, null);

            final String mimeType = TextUtils.isEmpty(attachment.mMimeType) ? "application/octet-stream"
                    : attachment.mMimeType;

            try {
                DownloadManager dm = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
                //TS: junwei-xu 2016-02-04 EMAIL BUGFIX-1531245 MOD_S
                //Note: should use media scanner, it will allow update the
                //media provider uri column in download manager's database.
                long id = dm.addCompletedDownload(attachment.mFileName, attachment.mFileName,
                        true /* use media scanner */, mimeType, absolutePath, size,
                        true /* show notification */);
                //TS: junwei-xu 2016-02-04 EMAIL BUGFIX-1531245 MOD_E
                contentUri = dm.getUriForDownloadedFile(id).toString();
            } catch (final IllegalArgumentException e) {
                LogUtils.d(LogUtils.TAG, e, "IAE from DownloadManager while saving attachment");
                throw new IOException(e);
            }
        } else {
            LogUtils.w(Logging.LOG_TAG, "Trying to save an attachment without external storage?");
            throw new IOException();
        }

        // Update the attachment
        cv.put(AttachmentColumns.SIZE, size);
        cv.put(AttachmentColumns.CONTENT_URI, contentUri);
        cv.put(AttachmentColumns.UI_STATE, UIProvider.UIPROVIDER_ATTACHMENTSTATE_SAVED);
        //TS: zheng.zou 2016-1-22 EMAIL BUGFIX-1431088 ADD_S
        if (realUri != null) {
            cv.put(AttachmentColumns.REAL_URI, realUri);
        }
        //TS: zheng.zou 2016-1-22 EMAIL BUGFIX-1431088 ADD_E
    } catch (IOException e) {
        LogUtils.e(Logging.LOG_TAG, e, "Fail to save attachment to storage!");
        // Handle failures here...
        cv.put(AttachmentColumns.UI_STATE, UIProvider.UIPROVIDER_ATTACHMENTSTATE_FAILED);
    }
    context.getContentResolver().update(uri, cv, null, null);
    //TS: wenggangjin 2014-12-11 EMAIL BUGFIX_868520 MOD_S
    // If this is an inline attachment, update the body
    if (contentUri != null && attachment.mContentId != null && attachment.mContentId.length() > 0) {
        Body body = Body.restoreBodyWithMessageId(context, attachment.mMessageKey);
        if (body != null && body.mHtmlContent != null) {
            cv.clear();
            String html = body.mHtmlContent;
            String contentIdRe = "\\s+(?i)src=\"cid(?-i):\\Q" + attachment.mContentId + "\\E\"";
            //TS: zhaotianyong 2015-03-23 EXCHANGE BUGFIX_899799 MOD_S
            //TS: zhaotianyong 2015-04-01 EXCHANGE BUGFIX_962560 MOD_S
            String srcContentUri = " src=\"" + contentUri + "\"";
            //TS: zhaotianyong 2015-04-01 EXCHANGE BUGFIX_962560 MOD_E
            //TS: zhaotianyong 2015-03-23 EXCHANGE BUGFIX_899799 MOD_E
            //TS: zhaotianyong 2015-04-15 EMAIL BUGFIX_976967 MOD_S
            try {
                html = html.replaceAll(contentIdRe, srcContentUri);
            } catch (PatternSyntaxException e) {
                LogUtils.w(Logging.LOG_TAG, "Unrecognized backslash escape sequence in pattern");
            }
            //TS: zhaotianyong 2015-04-15 EMAIL BUGFIX_976967 MOD_E
            cv.put(BodyColumns.HTML_CONTENT, html);
            Body.updateBodyWithMessageId(context, attachment.mMessageKey, cv);
            Body.restoreBodyHtmlWithMessageId(context, attachment.mMessageKey);
        }
    }
    //TS: wenggangjin 2014-12-11 EMAIL BUGFIX_868520 MOD_E
    return size;
}

From source file:cn.ucai.wechat.ui.SettingsActivity.java

void sendLogThroughMail() {
    String logPath = "";
    try {/*from   w w  w  . j a va2  s .  co  m*/
        logPath = EMClient.getInstance().compressLogs();
    } catch (Exception e) {
        e.printStackTrace();
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(SettingsActivity.this, "compress logs failed", Toast.LENGTH_LONG).show();
            }
        });
        return;
    }
    File f = new File(logPath);
    File storage = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
    if (f.exists() && f.canRead()) {
        try {
            storage.mkdirs();
            File temp = File.createTempFile("hyphenate", ".log.gz", storage);
            if (!temp.canWrite()) {
                return;
            }
            boolean result = f.renameTo(temp);
            if (result == false) {
                return;
            }
            Intent intent = new Intent(Intent.ACTION_SEND_MULTIPLE);
            intent.setData(Uri.parse("mailto:"));
            intent.putExtra(Intent.EXTRA_SUBJECT, "log");
            intent.putExtra(Intent.EXTRA_TEXT, "log in attachment: " + temp.getAbsolutePath());

            intent.setType("application/octet-stream");
            ArrayList<Uri> uris = new ArrayList<>();
            uris.add(Uri.fromFile(temp));
            intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris);
            startActivity(intent);
        } catch (final Exception e) {
            e.printStackTrace();
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(SettingsActivity.this, e.getLocalizedMessage(), Toast.LENGTH_LONG).show();
                }
            });
        }
    }
}

From source file:org.mozilla.gecko.updater.UpdateService.java

private File downloadUpdatePackage(UpdateInfo info, boolean overwriteExisting) {
    URL url = null;/*from www  . ja v  a 2 s  .c om*/
    try {
        url = info.uri.toURL();
    } catch (java.net.MalformedURLException e) {
        Log.e(LOGTAG, "failed to read URL: ", e);
        return null;
    }

    File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
    path.mkdirs();
    String fileName = new File(url.getFile()).getName();
    File downloadFile = new File(path, fileName);

    if (!overwriteExisting && info.buildID.equals(getLastBuildID()) && downloadFile.exists()) {
        // The last saved buildID is the same as the one for the current update. We also have a file
        // already downloaded, so it's probably the package we want. Verify it to be sure and just
        // return that if it matches.

        if (verifyDownloadedPackage(downloadFile)) {
            Log.i(LOGTAG, "using existing update package");
            return downloadFile;
        } else {
            // Didn't match, so we're going to download a new one.
            downloadFile.delete();
        }
    }

    if (!info.buildID.equals(getLastBuildID())) {
        // Delete the previous package when a new version becomes available.
        deleteUpdatePackage(getLastFileName());
    }

    Log.i(LOGTAG, "downloading update package");
    sendCheckUpdateResult(CheckUpdateResult.DOWNLOADING);

    OutputStream output = null;
    InputStream input = null;

    mDownloading = true;
    mCancelDownload = false;
    showDownloadNotification(downloadFile);

    try {
        NetworkInfo netInfo = mConnectivityManager.getActiveNetworkInfo();
        if (netInfo != null && netInfo.isConnected() && netInfo.getType() == ConnectivityManager.TYPE_WIFI) {
            mWifiLock.acquire();
        }

        URLConnection conn = openConnectionWithProxy(info.uri);
        int length = conn.getContentLength();

        output = new BufferedOutputStream(new FileOutputStream(downloadFile));
        input = new BufferedInputStream(conn.getInputStream());

        byte[] buf = new byte[BUFSIZE];
        int len = 0;

        int bytesRead = 0;
        int lastNotify = 0;

        while ((len = input.read(buf, 0, BUFSIZE)) > 0 && !mCancelDownload) {
            output.write(buf, 0, len);
            bytesRead += len;
            // Updating the notification takes time so only do it every 1MB
            if (bytesRead - lastNotify > 1048576) {
                mBuilder.setProgress(length, bytesRead, false);
                mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
                lastNotify = bytesRead;
            }
        }

        mNotificationManager.cancel(NOTIFICATION_ID);

        // if the download was canceled by the user
        // delete the update package
        if (mCancelDownload) {
            Log.i(LOGTAG, "download canceled by user!");
            downloadFile.delete();

            return null;
        } else {
            Log.i(LOGTAG, "completed update download!");
            return downloadFile;
        }
    } catch (Exception e) {
        downloadFile.delete();
        showDownloadFailure();

        Log.e(LOGTAG, "failed to download update: ", e);
        return null;
    } finally {
        try {
            if (input != null)
                input.close();
        } catch (java.io.IOException e) {
        }

        try {
            if (output != null)
                output.close();
        } catch (java.io.IOException e) {
        }

        mDownloading = false;

        if (mWifiLock.isHeld()) {
            mWifiLock.release();
        }
    }
}

From source file:com.kevin.cattalk.ui.SettingsFragment.java

void sendLogThroughMail() {
    String logPath = "";
    try {//from ww w .j a v a  2  s .c  om
        logPath = EMClient.getInstance().compressLogs();
    } catch (Exception e) {
        e.printStackTrace();
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(getActivity(), "compress logs failed", Toast.LENGTH_LONG).show();
            }
        });
        return;
    }
    File f = new File(logPath);
    File storage = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
    if (f.exists() && f.canRead()) {
        try {
            storage.mkdirs();
            File temp = File.createTempFile("hyphenate", ".log.gz", storage);
            if (!temp.canWrite()) {
                return;
            }
            boolean result = f.renameTo(temp);
            if (result == false) {
                return;
            }
            Intent intent = new Intent(Intent.ACTION_SEND_MULTIPLE);
            intent.setData(Uri.parse("mailto:"));
            intent.putExtra(Intent.EXTRA_SUBJECT, "log");
            intent.putExtra(Intent.EXTRA_TEXT, "log in attachment: " + temp.getAbsolutePath());

            intent.setType("application/octet-stream");
            ArrayList<Uri> uris = new ArrayList<>();
            uris.add(Uri.fromFile(temp));
            intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris);
            startActivity(intent);
        } catch (final Exception e) {
            e.printStackTrace();
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(getContext(), e.getLocalizedMessage(), Toast.LENGTH_LONG).show();
                }
            });
        }
    }
}

From source file:no.barentswatch.fiskinfo.MapActivity.java

private void runScheduledAlarm() {
    new FiskinfoScheduledTaskExecutor(2).scheduleAtFixedRate(new Runnable() {

        @Override/*  w  w  w .java 2s.  c om*/
        public void run() {
            // Need to get alarm status and handle kill
            if (!cacheDeserialized) {
                if (checkCacheWriterStatus()) {
                    String directoryPath = Environment
                            .getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString();
                    String directoryName = "FiskInfo";
                    String filename = "cachedResults";
                    String filePath = directoryPath + "/" + directoryName + "/" + filename;
                    tools = new FiskInfoUtility().deserializeFiskInfoPolygon2D(filePath);
                    cacheDeserialized = true;
                    // DEMO: HER LEGGER VI INN PUNKTENE SOM VI SKAL SKREMME
                    // FOLK MED!
                    // Point point = new Point(69.650543, 18.956831);
                    // tools.addPoint(point);
                }
            } else {
                if (alarmFiring) {
                    System.out.println("SHieeeeet");
                    notifyUserOfProximityAlert();
                } else {
                    double latitude, longitude = 0;
                    if (mGpsLocationTracker.canGetLocation()) {
                        latitude = mGpsLocationTracker.getLatitude();
                        cachedLat = latitude;
                        longitude = mGpsLocationTracker.getLongitude();
                        cachedLon = longitude;
                        System.out.println("Lat; " + latitude + "lon: " + longitude);
                        Log.i("GPS-LocationTracker", String.format("latitude: %s", latitude));
                        Log.i("GPS-LocationTracker", String.format("longitude: %s", longitude));
                    } else {
                        mGpsLocationTracker.showSettingsAlert();
                        return;
                    }
                    Point userPosition = new Point(cachedLat, cachedLon);
                    if (!tools.checkCollsionWithPoint(userPosition, Double.parseDouble(cachedDistance))) {
                        System.out.println("We no crash");
                        return;
                    }
                    // shieeeet
                    alarmFiring = true;
                }
            }

            System.out.println("BEEP");
        }

    }, 5, 20, TimeUnit.SECONDS); // <num1> is initial delay,<num2> is the subsequent delay between each call
}

From source file:com.raspi.chatapp.ui.chatting.ChatActivity.java

/**
 * will start the asyncTask to download the update
 *
 * @param version the version to download
 *///w  w  w .  ja v  a2s.c o m
private void downloadUpdate(String version) {
    MyFileUtils mfu = new MyFileUtils();
    // if we have access to the external storage
    if (mfu.isExternalStorageWritable()) {
        // get the default download location and execute the asyncTask
        UpdateAppAsyncTask asyncTask = new UpdateAppAsyncTask();
        File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS),
                version + ".apk");
        asyncTask.execute(new String[] { version + ".apk", file.getAbsolutePath() });
    } else {
        new AlertDialog.Builder(ChatActivity.this).setTitle(R.string.download_failed)
                .setNegativeButton(R.string.ok, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                }).show();
    }
}

From source file:com.andfchat.frontend.activities.ChatScreen.java

public void exportChat() {
    int permissionCheck = ContextCompat.checkSelfPermission(context,
            Manifest.permission.WRITE_EXTERNAL_STORAGE);

    if (ContextCompat.checkSelfPermission(context,
            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 {/*  w ww  .  ja va2  s. co  m*/
        String filename = "FListLog-" + chatroomManager.getActiveChat().getName() + "-"
                + System.currentTimeMillis() + ".txt";
        File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
        File file = new File(path, filename);

        try {
            path.mkdirs();

            OutputStream os = new FileOutputStream(file);
            os.write(Exporter.exportText(this, chatroomManager.getActiveChat()));
            os.close();

            ChatEntry entry = entryFactory.getNotation(charManager.findCharacter(CharacterManager.USER_SYSTEM),
                    R.string.exported, new Object[] { filename });
            chatroomManager.addMessage(chatroomManager.getActiveChat(), entry);

            // Tell the media scanner about the new file so that it is
            // immediately available to the user.
            MediaScannerConnection.scanFile(this, new String[] { file.toString() }, null,
                    new MediaScannerConnection.OnScanCompletedListener() {
                        @Override
                        public void onScanCompleted(String path, Uri uri) {

                        }
                    });
        } catch (IOException e) {
            Ln.w("ExternalStorage", "Error writing " + file, e);
            ChatEntry entry = entryFactory.getError(charManager.findCharacter(CharacterManager.USER_SYSTEM),
                    R.string.export_failed);
            chatroomManager.addMessage(chatroomManager.getActiveChat(), entry);
        }
    }

}

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

private void createProximityAlertSetupDialog() {
    final Dialog dialog = dialogInterface.getDialog(getActivity(), R.layout.dialog_proximity_alert_create,
            R.string.create_proximity_alert);

    Button setProximityAlertWatcherButton = (Button) dialog
            .findViewById(R.id.create_proximity_alert_create_alert_watcher_button);
    Button stopCurrentProximityAlertWatcherButton = (Button) dialog
            .findViewById(R.id.create_proximity_alert_stop_existing_alert_button);
    Button cancelButton = (Button) dialog.findViewById(R.id.create_proximity_alert_cancel_button);
    SeekBar seekbar = (SeekBar) dialog.findViewById(R.id.create_proximity_alert_seekBar);
    final EditText radiusEditText = (EditText) dialog.findViewById(R.id.create_proximity_alert_range_edit_text);
    final Switch formatSwitch = (Switch) dialog.findViewById(R.id.create_proximity_alert_format_switch);

    final double seekBarStepSize = (double) (getResources()
            .getInteger(R.integer.proximity_alert_maximum_warning_range_meters)
            - getResources().getInteger(R.integer.proximity_alert_minimum_warning_range_meters)) / 100;

    radiusEditText.setText(// w ww  . j a  v  a  2 s  .c om
            String.valueOf(getResources().getInteger(R.integer.proximity_alert_minimum_warning_range_meters)));

    formatSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (isChecked) {
                buttonView.setText(getString(R.string.range_format_nautical_miles));
            } else {
                buttonView.setText(getString(R.string.range_format_meters));
            }
        }
    });

    seekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            if (fromUser) {
                String range = String.valueOf(
                        (int) (getResources().getInteger(R.integer.proximity_alert_minimum_warning_range_meters)
                                + (seekBarStepSize * progress)));
                radiusEditText.setText(range);
            }
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {

        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {

        }
    });

    setProximityAlertWatcherButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String toastText;

            if (proximityAlertWatcher == null) {
                toastText = getString(R.string.proximity_alert_set);
            } else {

                toastText = getString(R.string.proximity_alert_replace);
            }

            if (proximityAlertWatcher != null) {
                proximityAlertWatcher.cancel(true);
            }

            mGpsLocationTracker = new GpsLocationTracker(getActivity());
            double latitude, longitude;

            if (mGpsLocationTracker.canGetLocation()) {
                latitude = mGpsLocationTracker.getLatitude();
                cachedLat = latitude;
                longitude = mGpsLocationTracker.getLongitude();
                cachedLon = longitude;
            } else {
                mGpsLocationTracker.showSettingsAlert();
                return;
            }

            if (formatSwitch.isChecked()) {
                cachedDistance = Double.valueOf(radiusEditText.getText().toString())
                        * getResources().getInteger(R.integer.meters_per_nautical_mile);
            } else {
                cachedDistance = Double.valueOf(radiusEditText.getText().toString());
            }

            dialog.dismiss();

            Response response;

            try {
                String apiName = "fishingfacility";
                String format = "OLEX";
                String filePath;
                String fileName = "collisionCheckToolsFile";

                response = barentswatchApi.getApi().geoDataDownload(apiName, format);

                if (response == null) {
                    Log.d(TAG, "RESPONSE == NULL");
                    throw new InternalError();
                }

                if (fiskInfoUtility.isExternalStorageWritable()) {
                    String directoryPath = Environment
                            .getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString();
                    String directoryName = "FiskInfo";
                    filePath = directoryPath + "/" + directoryName + "/";
                    InputStream zippedInputStream = null;

                    try {
                        TypedInput responseInput = response.getBody();
                        zippedInputStream = responseInput.in();
                        zippedInputStream = new GZIPInputStream(zippedInputStream);

                        InputSource inputSource = new InputSource(zippedInputStream);
                        InputStream input = new BufferedInputStream(inputSource.getByteStream());
                        byte data[];
                        data = FiskInfoUtility.toByteArray(input);

                        InputStream inputStream = new ByteArrayInputStream(data);
                        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
                        FiskInfoPolygon2D serializablePolygon2D = new FiskInfoPolygon2D();

                        String line;
                        boolean startSet = false;
                        String[] convertedLine;
                        List<Point> shape = new ArrayList<>();
                        while ((line = reader.readLine()) != null) {
                            Point currPoint = new Point();
                            if (line.length() == 0 || line.equals("")) {
                                continue;
                            }
                            if (Character.isLetter(line.charAt(0))) {
                                continue;
                            }

                            convertedLine = line.split("\\s+");

                            if (line.length() > 150) {
                                Log.d(TAG, "line " + line);
                            }

                            if (convertedLine[0].startsWith("3sl")) {
                                continue;
                            }

                            if (convertedLine[3].equalsIgnoreCase("Garnstart") && startSet) {
                                if (shape.size() == 1) {
                                    // Point

                                    serializablePolygon2D.addPoint(shape.get(0));
                                    shape = new ArrayList<>();
                                } else if (shape.size() == 2) {

                                    // line
                                    serializablePolygon2D.addLine(new Line(shape.get(0), shape.get(1)));
                                    shape = new ArrayList<>();
                                } else {

                                    serializablePolygon2D.addPolygon(new Polygon(shape));
                                    shape = new ArrayList<>();
                                }
                                startSet = false;
                            }

                            if (convertedLine[3].equalsIgnoreCase("Garnstart") && !startSet) {
                                double lat = Double.parseDouble(convertedLine[0]) / 60;
                                double lon = Double.parseDouble(convertedLine[1]) / 60;
                                currPoint.setNewPointValues(lat, lon);
                                shape.add(currPoint);
                                startSet = true;
                            } else if (convertedLine[3].equalsIgnoreCase("Brunsirkel")) {
                                double lat = Double.parseDouble(convertedLine[0]) / 60;
                                double lon = Double.parseDouble(convertedLine[1]) / 60;
                                currPoint.setNewPointValues(lat, lon);
                                shape.add(currPoint);
                            }
                        }

                        reader.close();
                        new FiskInfoUtility().serializeFiskInfoPolygon2D(filePath + fileName + "." + format,
                                serializablePolygon2D);

                        tools = serializablePolygon2D;

                    } catch (IOException e) {
                        e.printStackTrace();
                    } catch (ArrayIndexOutOfBoundsException e) {
                        Log.e(TAG, "Error when trying to serialize file.");
                        Toast error = Toast.makeText(getActivity(), "Ingen redskaper i omrdet du definerte",
                                Toast.LENGTH_LONG);
                        e.printStackTrace();
                        error.show();
                        return;
                    } finally {
                        try {
                            if (zippedInputStream != null) {
                                zippedInputStream.close();
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                } else {
                    Toast.makeText(v.getContext(), R.string.download_failed, Toast.LENGTH_LONG).show();
                    dialog.dismiss();
                    return;
                }

            } catch (Exception e) {
                Log.d(TAG, "Could not download tools file");
                Toast.makeText(getActivity(), R.string.download_failed, Toast.LENGTH_LONG).show();
            }

            runScheduledAlarm(getResources().getInteger(R.integer.zero),
                    getResources().getInteger(R.integer.proximity_alert_interval_time_seconds));

            Toast.makeText(getActivity(), toastText, Toast.LENGTH_LONG).show();
        }
    });

    if (proximityAlertWatcher != null) {
        TypedValue outValue = new TypedValue();
        stopCurrentProximityAlertWatcherButton.setVisibility(View.VISIBLE);

        getResources().getValue(R.dimen.proximity_alert_dialog_button_text_size_small, outValue, true);
        float textSize = outValue.getFloat();

        setProximityAlertWatcherButton.setTextSize(textSize);
        stopCurrentProximityAlertWatcherButton.setTextSize(textSize);
        cancelButton.setTextSize(textSize);

        stopCurrentProximityAlertWatcherButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                proximityAlertWatcher.cancel(true);
                proximityAlertWatcher = null;
                dialog.dismiss();
            }
        });
    }

    cancelButton.setOnClickListener(onClickListenerInterface.getDismissDialogListener(dialog));

    dialog.show();
}

From source file:com.apptentive.android.sdk.util.Util.java

/**
 * This function launchs the default app to view the selected file, based on mime type
 *
 * @param sourcePath/*from   ww w  . j av  a 2 s . com*/
 * @param selectedFilePath the full path to the local storage
 * @param mimeTypeString   the mime type of the file to be opened
 * @return true if file can be viewed
 */
public static boolean openFileAttachment(final Context context, final String sourcePath,
        final String selectedFilePath, final String mimeTypeString) {
    if ((Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())
            || !Environment.isExternalStorageRemovable())
            && hasPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {

        File selectedFile = new File(selectedFilePath);
        String selectedFileName = null;
        if (selectedFile.exists()) {
            selectedFileName = selectedFile.getName();
            final Intent intent = new Intent();
            intent.setAction(android.content.Intent.ACTION_VIEW);
            /* Attachments were downloaded into app private data dir. In order for external app to open
             * the attachments, the file need to be copied to a download folder that is accessible to public
            * The folder will be sdcard/Downloads/apptentive-received/<file name>
            */
            File downloadFolder = Environment
                    .getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
            File apptentiveSubFolder = new File(downloadFolder, "apptentive-received");
            if (!apptentiveSubFolder.exists()) {
                apptentiveSubFolder.mkdir();
            }

            File tmpfile = new File(apptentiveSubFolder, selectedFileName);
            String tmpFilePath = tmpfile.getPath();
            // If destination file already exists, overwrite it; otherwise, delete all existing files in the same folder first.
            if (!tmpfile.exists()) {
                String[] children = apptentiveSubFolder.list();
                if (children != null) {
                    for (int i = 0; i < children.length; i++) {
                        new File(apptentiveSubFolder, children[i]).delete();
                    }
                }
            }
            if (copyFile(selectedFilePath, tmpFilePath) == 0) {
                return false;
            }

            intent.setDataAndType(Uri.fromFile(tmpfile), mimeTypeString);
            try {
                context.startActivity(intent);
                return true;
            } catch (ActivityNotFoundException e) {
                ApptentiveLog.e("Activity not found to open attachment: ", e);
            }
        }
    } else {
        Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(sourcePath));
        if (Util.canLaunchIntent(context, browserIntent)) {
            context.startActivity(browserIntent);
        }
    }
    return false;
}

From source file:com.christophergs.mbientbasic.NavigationActivity.java

public void onSaveButtonPressed(int position) {
    Log.i(TAG, String.format("SAVE TEST: %d", position));
    FragmentManager fragmentManager = getSupportFragmentManager();
    BothFragment f1 = (BothFragment) fragmentManager
            .findFragmentByTag("com.christophergs.mbientbasic.BothFragment");
    GyroFragmentNew f2 = (GyroFragmentNew) fragmentManager
            .findFragmentByTag("com.christophergs.mbientbasic.GyroFragmentNew");

    String delete_filename = String.format("METAWEAR.csv");
    File path = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS),
            delete_filename);/*from  ww  w .  j  a  va2s.  co m*/

    //delete the csv file if it already exists (will be from older recordings)
    f1.prep(path);
    String filename = f1.saveData(false); //f1 is the accelerometer, we keep the header
    String filename2 = f2.saveData(true); //f2 is the gyro, we remove the header

    sendFile();

    /*
    if (filename != null) {
    File dataFile = getFileStreamPath(filename);
    Uri contentUri = FileProvider.getUriForFile(this, "com.mbientlab.metawear.app.fileprovider", dataFile);
            
    Intent intent = new Intent(Intent.ACTION_SEND);
    intent.setType("text/plain");
    intent.putExtra(Intent.EXTRA_SUBJECT, filename);
    intent.putExtra(Intent.EXTRA_STREAM, contentUri);
    startActivity(Intent.createChooser(intent, "Saving Data"));
    }*/
}