Я использую DownloadManager для загрузки и трансляцию для завершения.Через некоторое время Android его убивает, и трансляция так и не заканчивается (загрузка продолжается после того, как приложение не работает)
<pre>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<DocumentSnapshot>() {
@Override
public void onComplete(@NonNull Task<DocumentSnapshot> 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();
}
}
<code>
Я даже добавил эту ветку, чтобы контролировать Download%, чтобы "удерживать" приложение живым,но это бесполезно.
Как я могу получить мое приложение, чтобы закончить загрузку, чтобы запустить другой сервис?Мне нужно распаковать файл после его загрузки без участия пользователя.
Спасибо!