简体   繁体   中英

Copy big file from SD card to internal memory on android

I'm new to Android and I want to copy a big file (approx. 2GB) chosen by the user (so I guess it should have permissions by default) to the internal memory. I already have the permissions added in AndroidManifest but I don't know how (and if I need to) use the Android FileProivder . I would also like to know how this process can happen on another thread such that the app is not blocked during the process and it can show the progress.

You could use a foreground service to do this and make sure the process doesn't get interrupted.

Build the service:

public class CopyService extends Service {
  @Override
  public void onCreate() {

  }

  @Override
  public int onStartCommand(final Intent intent, int flags, int startId) {
    // Run the moving code here
    return START_NOT_STICKY;
  }
}

It's important that you launch it as a foreground service (add permission in manifest), so it doesn't get destroyed after some time. You'll be required to add a notification then, which you can use for progress.

Read further on services: https://developer.android.com/guide/components/services

As @blackapps pointed out it would be wise decision to check the permission and only start the service if it's granted. I usually check if the permission is granted, if not I request it, if it is I follow. Then I check for it once again so I can see if the user granted it or not.

Google has a great article on how to request permissions: https://developer.android.com/training/permissions/requesting

How to move the file though? Here is the code I use in my own app:

private static void moveFile(File from, File to) {
  InputStream inputStream;
  OutputStream outputStream;

  try {
    inputStream = new FileInputStream(from);
    outputStream = new FileOutputStream(to);

    byte[] buffer = new byte[1024];

    while (inputStream.read(buffer) > 0) {
      outputStream.write(buffer);
    }

    inputStream.close();
    outputStream.close();

    // You may wish not to do this if you want to keep the original file
    from.delete();

    Log.i(LOG_TAG, "File copied successfully");

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

  // Stop service here
}

The code you'd like to run inside the service should be placed inside onStartCommand()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM