Android: How to run asynctask from different class file?

后端 未结 4 2002
醉酒成梦
醉酒成梦 2020-12-01 02:18

When I use my code in one class file, it runs perfectly:

package com.example.downloadfile;

import java.io.File;
import java.io.FileOutputStream;
import java         


        
相关标签:
4条回答
  • 2020-12-01 02:43

    If you can somehow pass the Activity class or its context to the AsyncTask that will solve your issue for showing dialog. You would need to include another parameter together with the URL you are sending and put that parameter in a Context variable. And then whenever you need the dialog you use that context variable to show it.

    If the dialog does not have a Context from which to show it will definitely run into runtime errors.

    Update (put my comment up here as well): here we go... found a good example that you can modify to make use for your case. It's at brighthub.com/mobile/google-android/articles/82805.aspx. Scroll down to Source Code section and have a look at the code for WebServiceAsyncTask and WebServiceBackgroundActivity.

    0 讨论(0)
  • 2020-12-01 02:58

    I know its too late to help you but for others this may help.

    Its so simple just Simply build an object of main class and than call the inner class like this

     OuterMainClass outer = new OuterMainClass();
           outer.new InnerAsyncClass(param)
             .execute();
    

    Thanks

    0 讨论(0)
  • 2020-12-01 02:58

    Actual problem can be class level error, you might not be placing async class and download class in same package. Other problem I can see is async class using showDialog(), onCreateDialog() etc., which is available only if your class extends Activity.

    0 讨论(0)
  • 2020-12-01 03:00

    Some changes in your code will make it work :

    public class DownloadFileAsync extends AsyncTask<String, String, String> {
    public static final int DIALOG_DOWNLOAD_PROGRESS = 0;
    private ProgressDialog mProgressDialog;
    
    private Context context;
    
    public DownloadFileAsync(Context context) 
    {
        this.context = context;
         mProgressDialog = new ProgressDialog(context);
         mProgressDialog.setMessage("Downloading file..");
         mProgressDialog.setIndeterminate(false);
         mProgressDialog.setMax(100);
         mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
         mProgressDialog.setCancelable(true);
    
    }
    
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        mProgressDialog.show();
    }
    
    @Override
    protected String doInBackground(String... aurl) {
    
        try {
            File root = Environment.getExternalStorageDirectory();
            URL u = new URL(aurl[0]);
            HttpURLConnection c = (HttpURLConnection) u.openConnection();
            c.setRequestMethod("GET");
            c.setDoOutput(true);
            c.connect();
    
            int lenghtOfFile = c.getContentLength();
    
            FileOutputStream f = new FileOutputStream(new File(root + "/download/", aurl[1]));
    
            InputStream in = c.getInputStream();
    
            byte[] buffer = new byte[1024];
            int len1 = 0;
            long total = 0;
    
            while ((len1 = in.read(buffer)) > 0) {
                total += len1; //total = total + len1
                publishProgress("" + (int)((total*100)/lenghtOfFile));
                f.write(buffer, 0, len1);
            }
            f.close();
        } catch (Exception e) {
            Log.d("Downloader", e.getMessage());
        }
    
        return null;
    
    }
    
    protected void onProgressUpdate(String... progress) {
         Log.d("ANDRO_ASYNC",progress[0]);
         mProgressDialog.setProgress(Integer.parseInt(progress[0]));
    }
    
    @Override
    protected void onPostExecute(String unused) {
        mProgressDialog.dismiss();
    }
    
    
    }
    

    And DownloadFile Class :

    public class DownloadFile extends Activity {
    
    
    private static String fileName = "yo.html";
    private static String fileURL = "http://mydomain.com/tabletcms/tablets/tablet_content/000002/form/Best%20Form%20Ever/html";
    
     @Override
     public void onCreate(Bundle savedInstanceState) 
     {
        super.onCreate(savedInstanceState);
    
        setContentView(R.layout.main);
        TextView tv = new TextView(this);
        tv.setText("This is download file program with asynctask... ");
        tv.append("\nYo, this line is appended!");
    
        startDownload();
    
     }
    
    private void startDownload() {
        new DownloadFileAsync(this).execute(fileURL,fileName);
    }
    
    }
    
    0 讨论(0)
提交回复
热议问题