Pergunta

I created a AsyncTask class that this class get my latest update. everything is ok but onPostExecute method immediately called after doInBackground method While the downloading is not finished !

how can I do fixed it ?

public class UpdateApp extends AsyncTask<String,Void,Void>{
    private Context context;
    public void setContext(Context contextf){
        context = contextf;
    }



    @Override
    protected void onPostExecute(Void result) {
        // TODO Auto-generated method stub
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(Uri.fromFile(new File(Environment.getExternalStorageDirectory()
                + "/Updates/update"+now+".apk")), "application/vnd.android.package-archive");
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // without this flag android returned a intent error!
        context.startActivity(intent);
        rotateimageview.stopAnimation();
        super.onPostExecute(result);
    }



    @Override
    protected void onPreExecute() {
        // TODO Auto-generated method stub
        rotateimageview.startAnimation();
        super.onPreExecute();
    }



    @SuppressLint("SimpleDateFormat")
    @Override
    protected Void doInBackground(String... arg0) {
        String DATE_FORMAT_NOW = "yyyy-MM-dd HH:mm:ss";
        Calendar cal = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_NOW);
        String now =  sdf.format(cal.getTime());
        String url = arg0[0];;

        File direct = new File(Environment.getExternalStorageDirectory()
                + "/Updates");

        if (!direct.exists()) {
            direct.mkdirs();
        }

        DownloadManager mgr = (DownloadManager) getActivity().getSystemService(Context.DOWNLOAD_SERVICE);

        Uri downloadUri = Uri.parse(url);
        DownloadManager.Request request = new DownloadManager.Request(
                downloadUri);

        request.setAllowedNetworkTypes(
                DownloadManager.Request.NETWORK_WIFI
                        | DownloadManager.Request.NETWORK_MOBILE)
                .setAllowedOverRoaming(false).setTitle(getResources()
                        .getString(R.string.updating_downloadmanager_title).toString())
                .setDescription(getResources().getString(R.string.updating_downloadmanager_des).toString())
                .setDestinationInExternalPublicDir("/Updates", "update"+now+".apk");

        mgr.enqueue(request);

        return null;    
}  


}
Foi útil?

Solução

When you queue something with the DownloadManager, the enqueue call returns immediately (thus it appears that your task has completed).

There are two potential fixes:

  1. The preferred way to use DownloadManager is to implement a broadcast receiver to receive a broadcast when the download completes. As Merlevede points out, then you don't even use an AsyncTask.
  2. If you really need to keep your async task or don't want to implement the broadcast receiver, you could loop in your doInBackground and query the download manager to check status, hopefully sleeping some time between checks. Given the necessity of polling and sleeping this really shouldn't be a preferred option (and, theoretically, your task could get killed by the O/S if the app is put in the background, so you're not guaranteed to get the result).

Outras dicas

That's because the enqueue(request) method is asynchoronous, meaning it will return immediately even if it hasn't finished the job. Thus, onPostExecute is called even if the download is still in progress.

My suggestion is getting rid of the AsyncTask completely, because the request is handled in the background anyway.

To know when the download is finished you use a BroadcastReceiver. Check this article for a good example.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top