[英]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.