Skip to content

Instantly share code, notes, and snippets.

@KamilLelonek
Created August 30, 2013 12:46
Show Gist options
  • Save KamilLelonek/6389471 to your computer and use it in GitHub Desktop.
Save KamilLelonek/6389471 to your computer and use it in GitHub Desktop.
[Android] Activity used for copying selected files from anywhere on device to local data isolated storage.
package com.example.copy;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import android.app.Activity;
import android.app.DownloadManager;
import android.app.DownloadManager.Query;
import android.app.DownloadManager.Request;
import android.app.ProgressDialog;
import android.content.ActivityNotFoundException;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.util.Patterns;
import android.view.Gravity;
/**
* Requires: android:minSdkVersion="9"
*
* <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
* <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
* <uses-permission android:name="android.permission.INTERNET" />
* <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
*
* <activity android:name=".CopyFileActivity"
* android:screenOrientation="portrait" />
*
* USAGE:
*
* public void selectFile(View w) { startActivityForResult(new Intent(this,
* CopyFileActivity.class), RESULT_CODE); }
*
* @Override protected void onActivityResult(int requestCode, int resultCode,
* Intent data) { if (requestCode == RESULT_CODE && resultCode ==
* RESULT_OK && data != null) { String fileName =
* data.getStringExtra(CopyFileActivity.RESULT); } }
*/
public class CopyFileActivity extends Activity {
private static final String TAG = "CopyFileActivity";
private static final int RESULT_CODE = 0x321;
private static final int DEFAULT_BUFFER_SIZE = 1024/* bytes */* 1024/* kilobytes */* 10/* megabytes */;
private static final String DEFAULT_MIME_TYPE = "*/*";
public static final String RESULT = "FILE_NAME";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
showFileChooser();
}
private void showFileChooser() {
try {
startActivityForResult(
Intent.createChooser(getIntentForChoosingFiles(), "Select a file for GD App"),
RESULT_CODE);
}
catch (ActivityNotFoundException e) {
cancelAndFinish(e);
}
}
private void cancelAndFinish(ActivityNotFoundException e) {
Log.e(TAG, e.getMessage());
setResult(RESULT_CANCELED);
finish();
}
private Intent getIntentForChoosingFiles() {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType(DEFAULT_MIME_TYPE);
return intent;
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_CODE && resultCode == RESULT_OK && data != null) {
copyFile(data.getData());
}
}
private void copyFile(final Uri uri) {
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
new CopyFileAsyncTask().execute(uri);
}
}, 100);
}
private class CopyFileAsyncTask extends AsyncTask<Uri, Void, String> {
private static final String TYPE_CONTENT = "content";
private static final String TYPE_FILE = "file";
private DownloadManager downloadManager;
private ProgressDialog progressDialog;
private boolean isDownloading = false;
private long enqueue;
private final BroadcastReceiver downloadCompleteReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
isDownloading = false;
String oldFileName = getFileFromDownloadManager(enqueue);
String fileName = copyFile(Uri.parse(oldFileName));
setResultAndFinish(fileName);
unregisterReceiver(this);
}
}
};
public CopyFileAsyncTask() {
this.progressDialog = new ProgressDialog(CopyFileActivity.this);
progressDialog.setMessage("Copying files..");
progressDialog.getWindow().setGravity(Gravity.CENTER);
}
@Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog.show();
}
@Override
protected String doInBackground(Uri... uris) {
return copyFile(uris[0]);
}
@Override
protected void onPostExecute(String fileName) {
super.onPostExecute(fileName);
if (!isDownloading) {
setResultAndFinish(fileName);
}
}
private void setResultAndFinish(String fileName) {
progressDialog.dismiss();
setResult(RESULT_OK, getResultIntent(fileName));
Log.d(TAG, "If no errors before, file should be now in /" + fileName);
finish();
}
private Intent getResultIntent(String fileName) {
Intent intent = new Intent();
intent.putExtra(RESULT, fileName);
return intent;
}
private String copyFile(Uri uri) {
String path = getPath(uri);
if (TextUtils.isEmpty(path)) {
Log.e(TAG, "Can't read path.");
return null;
}
Log.d(TAG, "Copying from " + path);
String fileName = Uri.parse(path).getLastPathSegment(); // in case of TYPE_CONTENT
copyFile(path, fileName);
return fileName;
}
private String getPath(Uri uri) {
String scheme = uri.getScheme();
if (TYPE_FILE.equalsIgnoreCase(scheme)) return uri.getPath();
else if (TYPE_CONTENT.equalsIgnoreCase(scheme)) return getFilePathFromMedia(uri);
return "";
}
private String getFilePathFromMedia(Uri uri) {
String data = "_data";
String[] projection = { data };
Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
int column_index = cursor.getColumnIndex(data);
if (cursor.moveToFirst()) {
String filePath = cursor.getString(column_index);
cursor.close();
return filePath;
}
return "";
}
private void copyFile(String oldFileName, String newFileName) {
if (Patterns.WEB_URL.matcher(oldFileName).matches()) {
if (isNetworkAvailable()) {
downloadFileFromUrl(oldFileName);
}
else {
Log.e(TAG, "No internet connection. File neither downloaded nor copied.");
}
}
else {
File oldFile = new File(oldFileName);
File newFile = new File(getFilesDir(), newFileName);
copyFile(oldFile, newFile);
}
}
public boolean isNetworkAvailable() {
return ((ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo() != null;
}
private void downloadFileFromUrl(String fileUrl) {
registerDownloadReceiver();
downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
Request request = new Request(Uri.parse(fileUrl));
enqueue = downloadManager.enqueue(request);
isDownloading = true;
}
private void registerDownloadReceiver() {
registerReceiver(downloadCompleteReceiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
}
private String getFileFromDownloadManager(long enqueue) {
Query query = new Query();
query.setFilterById(enqueue);
Cursor c = downloadManager.query(query);
if (c.moveToFirst()) {
int columnIndex = c.getColumnIndex(DownloadManager.COLUMN_STATUS);
if (DownloadManager.STATUS_SUCCESSFUL == c.getInt(columnIndex)) {
String uriString = c.getString(c.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
c.close();
return uriString;
}
}
Log.e(TAG, "Downloading file not successful. Malformed Url or no internet connection");
return null;
}
private void copyFile(File oldFile, File newFile) {
InputStream in = null;
OutputStream out = null;
int copiedBytesSize = 0;
try {
try {
in = new BufferedInputStream(new FileInputStream(oldFile));
out = new BufferedOutputStream(new FileOutputStream(newFile));
copiedBytesSize = copyStreams(in, out);
Log.d(TAG, "Copied bytes: " + copiedBytesSize);
}
finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
catch (IOException e) {
Log.e(TAG, e.getMessage());
}
}
private int copyStreams(InputStream in, OutputStream out) throws IOException {
byte[] bytes = new byte[DEFAULT_BUFFER_SIZE];
int copiedBytesSize = 0;
int currentByte = 0;
while (-1 != (currentByte = in.read(bytes))) {
out.write(bytes, 0, currentByte);
copiedBytesSize += currentByte;
}
return copiedBytesSize;
}
}
public static void clearCache(final Context context) {
new Thread() {
@Override
public void run() {
File dataDirectory = context.getFilesDir();
Log.d(TAG, "Deleting: " + dataDirectory.getPath());
deleteRecursive(dataDirectory);
}
private void deleteRecursive(File rootPath) {
if (rootPath.isDirectory()) {
for (File fileOrFolder : rootPath.listFiles()) {
deleteRecursive(fileOrFolder);
}
}
rootPath.delete();
}
}.start();
}
}
@KamilLelonek
Copy link
Author

    private static boolean copyFile(String sourceFileName, String destinationFileName) {
        File sourceFile = new File(sourceFileName);
        File destinationFile = new File(destinationFileName);
        return copyFile(sourceFile, destinationFile);
    }

    private static boolean copyFile(File sourceFile, File destinationFile) {
        FileInputStream sourceStream = null;
        FileOutputStream destinationStream = null;
        try {
            sourceStream = new FileInputStream(sourceFile);
            destinationStream = new FileOutputStream(destinationFile);

            FileChannel destinationFileChannel = destinationStream.getChannel();
            FileChannel sourceFileChannel = sourceStream.getChannel();

            long fileSize = sourceFileChannel.size();
            int startPosition = 0;

            destinationFileChannel.transferFrom(sourceFileChannel, startPosition, fileSize);

            return true;
        }
        catch (IOException e) {
            // TODO log "I/O Error: " + e.getMessage()
            return false;
        }
        finally {
            // formatter:off
            try { sourceStream.close(); } catch (Exception e) { /* TODO log "Error closing source stream." */ }
            try { destinationStream.close(); } catch (Exception e) { /* TODO log "Error closing destination stream." */ }
            // formatter:on
        }
    }

@sam3961
Copy link

sam3961 commented Oct 28, 2016

Bro where it copies the file?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment