繁体   English   中英

将大文件从 SD 卡复制到 android 上的内部 memory

[英]Copy big file from SD card to internal memory on android

我是 Android 的新手,我想将用户选择的一个大文件(大约 2GB)复制到内部 memory(所以我猜它应该默认具有权限)。 我已经在 AndroidManifest 中添加了权限,但我不知道如何(以及是否需要)使用 Android FileProivder 我还想知道这个过程如何在另一个线程上发生,这样应用程序在这个过程中不会被阻塞,它可以显示进度。

您可以使用前台服务来执行此操作,并确保该过程不会被中断。

构建服务:

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;
  }
}

将它作为前台服务启动很重要(在清单中添加权限),因此它不会在一段时间后被破坏。 然后,您将需要添加一个通知,您可以将其用于进度。

进一步阅读服务: https://developer.android.com/guide/components/services

正如@blackapps 指出的那样,检查许可并仅在获得许可时才启动服务是明智的决定。 我通常检查是否授予权限,如果没有我请求它,如果它是我遵循。 然后我再次检查它,以便查看用户是否授予它。

谷歌有一篇关于如何请求权限的好文章: https://developer.android.com/training/permissions/requesting

但是如何移动文件? 这是我在自己的应用程序中使用的代码:

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
}

你想在服务中运行的代码应该放在 onStartCommand()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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