【问题标题】:Copy big file from SD card to internal memory on android将大文件从 SD 卡复制到 Android 上的内部存储器
【发布时间】:2020-02-22 17:08:23
【问题描述】:

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

【问题讨论】:

  • 您不需要使用文件提供程序,复制小文件或大文件的代码是相同的。
  • 在 manifest 中请求权限是不够的。您应该添加运行时权限的代码。好吧,并非总是...取决于路径。
  • 一个代码 sn-p 会有所帮助:)
  • 什么的代码 sn-p?
  • 目标是经典文件路径。因此,复制是(在循环中)从所选 uri 上的输入流中读取字节,然后将字节写入 FileOutputStream。我从来没有用 copyDocument() 尝试过这样的场景。

标签: java android android-permissions file-permissions android-sdcard


【解决方案1】:

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

构建服务:

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

Google 有一篇关于如何请求权限的精彩文章: 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() 中

【讨论】:

  • so I can see if the user granted it or not. If no - I'd stop the service with stopSelf();在获得权限之前不要启动服务。
  • 这可能是一个更好的解决方案。没有考虑到这一点。会更新我的答案
猜你喜欢
  • 1970-01-01
  • 2020-01-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多