private void downloadListener(final DownloadManager downloadManager,final long id,final String path)
{
//Send intent action when mission successed/failed.
Thread StatusSender=new Thread(new Runnable() {
@Override
public void run() {
synchronized (this)
{
Cursor cursor=null;
DownloadManager.Query query=new DownloadManager.Query();
query.setFilterById(id);
boolean downloading=true;
while(downloading)
{
try{
Thread.sleep(3000);
cursor=downloadManager.query(query);
if(cursor!=null&&cursor.moveToFirst())
{
Intent intent=new Intent();
int state=cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS));
switch(state)
{
case DownloadManager.STATUS_SUCCESSFUL:
intent.setAction(String.valueOf(id)+" download Successed.");
sendBroadcast(intent);
downloading=false;
break;
case DownloadManager.STATUS_FAILED:
downloadManager.remove(id);
downloading=false;
intent.setAction(String.valueOf(id)+" download Fail.");
sendBroadcast(intent);
break;
case DownloadManager.STATUS_PAUSED:
case DownloadManager.STATUS_PENDING:
case DownloadManager.STATUS_RUNNING:
break;
}
}
}catch (Exception e)
{
e.printStackTrace();
}
finally {
cursor.close();
}
}
}
}
});
StatusSender.start();
//Listen intent action
IntentFilter DLListener=new IntentFilter();
DLListener.addAction(String.valueOf(id)+" download Successed.");
DLListener.addAction(String.valueOf(id)+" download Fail.");
DL=new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(String.valueOf(id)+" download Successed."))
{
//Install
Install();
latch.countDown();
}
else if(intent.getAction().equals(String.valueOf(id)+" download Fail."))
{
String Str;
Str="[Download] Download "+String.valueOf(id)+" failed.\n"
+"[Download] Remove "+String.valueOf(id)+".\n";
Log.i(TAG,Str);
downloadManager.remove(id);
String apk="apk";
String url="url";
//retry download
doDownload(apk,path,url);
}
}
};
registerReceiver(DL,DLListener);
}