java下载大文件怎么处理_java - 尝试下载大文件(200MB + - 堆栈内存溢出

我正在使用DownloadManager处理下载,并使用广播来获取完成。 一段时间后,Android将其杀死,并且广播永远无法完成(应用程序死后继续下载)

public class Service_Downloading extends JobIntentService {

private static String TAG = "MainService";

public static final int JOB_ID = 0x01;

//private FirebaseAuth mAuth;

private String acao = "";

private long id_download;

private String get_zip_name = "";

private String ZIP_PATH = "zip_path";

private String PRODUCT = "product";

public static void enqueueWork(Context context, Intent work) {

Log.i(TAG, "Service Downloading");

MainActivity.getInstance().finish();

enqueueWork(context, Service_Downloading.class, JOB_ID, work);

}

@Override

protected void onHandleWork(@NonNull final Intent intent) {

Log.i(TAG, "on Handle Intent do Main Service");

// Access a Cloud Firestore instance

FirebaseFirestore db = FirebaseFirestore.getInstance();

String device = Build.SERIAL;

Log.i(TAG, "Serial: " + device);

//accessing the document relative from that device.

DocumentReference docRef = db.collection("Custom_MTL").document(device);

docRef.get().addOnCompleteListener(new OnCompleteListener() {

@Override

public void onComplete(@NonNull Task task) {

if (task.isSuccessful()) {

DocumentSnapshot document = task.getResult();

if (document.exists()) {

//get the product custom file's to do the download.

get_zip_name = (String) document.get(PRODUCT);

//Log.d(TAG, "ZipNameFirebase " + get_zip_name);

downloadFile(getApplicationContext(), "customization", ".zip",

DIRECTORY_DOWNLOADS, get_zip_name);

} else {

Log.d(TAG, "No such document");

}

} else {

Log.d(TAG, "Get failed with ", task.getException());

}

}

});

}

public void downloadFile(Context context, String filename, String fileextention, final String

destination, String url) {

Log.i(TAG, "Method: downloadFile");

// create an IntentFilter with action download complete

String downloadCompleteIntentName = DownloadManager.ACTION_DOWNLOAD_COMPLETE;

final IntentFilter downloadCompleteIntentFilter = new

IntentFilter(downloadCompleteIntentName);

//Broadcast Receiver to detect the download finish

BroadcastReceiver downloadCompleteReceiver = new BroadcastReceiver() {

@Override

public void onReceive(Context context, Intent intent) {

long id = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, 0L);

Log.i(TAG, "Id at broadcast: " + id);

Log.i(TAG, "Id Download out of broadcast: " + id_download);

if (id != id_download) {

Log.v(TAG, "Download's id is different: " + id);

return;

} else {

DownloadManager downloadManager = (DownloadManager)

context.getSystemService(Context.DOWNLOAD_SERVICE);

DownloadManager.Query query = new DownloadManager.Query();

query.setFilterById(id);

Cursor cursor = downloadManager.query(query);

if (!cursor.moveToFirst()) {

Log.e(TAG, "Empty row");

return;

} else {

int statusIndex = cursor.getColumnIndex(DownloadManager.COLUMN_STATUS);

if (DownloadManager.STATUS_SUCCESSFUL != cursor.getInt(statusIndex)) {

Log.w(TAG, "Download Failed");

return;

} else {

int uriIndex = cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI);

String downloadedPackageUriString = cursor.getString(uriIndex);

Log.i(TAG, "Equals Ids" + id);

long aux_id = id;

acao = intent.getAction();

//saving the download id to be used in the future.

SharedPreferences settings = context.getSharedPreferences("DownloadIDS",

0);

SharedPreferences.Editor editor = settings.edit();

editor.putLong("savedDownloadIds", id);

editor.commit();

//saving the file's path and name downloaded to be used onBootCompleted

SharedPreferences settings2 =

context.getSharedPreferences("PathFolderDownloaded", 0);

SharedPreferences.Editor editor2 = settings2.edit();

editor2.putString("path_file", downloadedPackageUriString);

editor2.putString("zip_name", get_zip_name);

editor2.commit();

Service_DownCompleted.enqueueWork(context, new

Intent().putExtra("path_downloaded", downloadedPackageUriString));

getApplicationContext().unregisterReceiver(this);

}

}

}

}

};

context.registerReceiver(downloadCompleteReceiver, downloadCompleteIntentFilter);

File customFile = new

File(getApplicationContext().getExternalFilesDir(DIRECTORY_DOWNLOADS).getAbsolutePath() ,

"customization.zip");

Log.i(TAG,"CustomFileCheck: "+customFile.getAbsolutePath());

if(customFile.exists())

{

customFile.delete();

}

else

{

Log.i(TAG,"CustomFileCheck: "+"OK For Download");

}

//Below we set the methods to download the file in background.

Uri uri = Uri.parse(url);

DownloadManager.Request request = new DownloadManager.Request(uri);

request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI);

request.setDescription("Downloading " + "Zip da Multilaser");

request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);

request.setDestinationInExternalFilesDir(context, destination, filename + fileextention);

DownloadManager downloadManager = (DownloadManager)

context.getSystemService(Context.DOWNLOAD_SERVICE);

//saving the download's id.

final DownloadManager manager = (DownloadManager)

getSystemService(Context.DOWNLOAD_SERVICE);

id_download = downloadManager.enqueue(request);

Log.i(TAG,"Download Starting...");

try {

Thread.sleep(1000);

} catch (InterruptedException e) {

e.printStackTrace();

}

new Thread(new Runnable() {

@Override

public void run() {

boolean downloading = true;

int old_dl_progress=0;

Log.i(TAG,"Download Progress: " + old_dl_progress + "%");

try {

while (downloading) {

DownloadManager.Query q = new DownloadManager.Query();

q.setFilterById(id_download);

Cursor cursor = manager.query(q);

cursor.moveToFirst();

int bytes_downloaded = cursor.getInt(cursor

.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR));

int bytes_total =

cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES));

if (cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS)) ==

DownloadManager.STATUS_SUCCESSFUL) {

downloading = false;

}

final double dl_progress = (int) ((bytes_downloaded * 100l) / bytes_total);

if((int)dl_progress > old_dl_progress) {

old_dl_progress =(int)dl_progress;

Log.i(TAG, "Download Progress: " + old_dl_progress + "%");

}

cursor.close();

try {

Thread.sleep(1000);

} catch (InterruptedException e) {

e.printStackTrace();

}

}

}catch (CursorIndexOutOfBoundsException e)

{

Log.i(TAG,"Download Canceled or Unexpected Error: "+e);

}

}

}).start();

}

}

我什至添加了此线程来控制Download%以“保持”应用程序的生命,但这没有用。

如何获得我的应用程序以完成下载以启动其他服务? 下载文件后,我需要解压缩文件,而无需用户干预。

谢谢!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值