2013-08-05 33 views
0

你好,我正在写一个下载项目,我卡在这里。AsyncTask如何从MainActivity获得进度

@Override 
protected void onProgressUpdate(Integer... progress) { 

} 

//I'm using in my mainactivity like that 
Download download = new Download(); 
download.execute("http://"); 

我想更新的时候才能进步,是的,我可以用onProgressUpdate做到这一点,但我想知道我可以从我的mainactivity我的意思是,其中i称为类得到它。我喜欢那种有趣的课程,因为我可以轻松地使用他们的每一个项目。谢谢btw原谅我的语法。

+0

http://stackoverflow.com/questions/3028306/download-a-file-with-android-and-showing-在正在进行的-IN-A-progressdialog/3028660#3028660 –

回答

0

我可以看到两个选项:

你要么通过您希望用构造显示进度,您的AsyncTask,然后你存储的对象是:

private ProgressObject mObject; 
public void MyAsyncTask(ProgressObject object) { 
    mObject = object 
} 

而且在更新中在onProgress()方法:

object.setProgress(); //assuming the ProgressObject has a method setProgress() obviously 

或者你可以建立某种形式的名单ENER:

public interface ProgressListener() { 
    public void onProgress(int progress); 
} 
private mProgressListener; 
public void MyAsyncTask(ProgressListener listener) { 
    mProgressListener = listener; 
} 

然后在onProgress()方法使用它:

mProgressListener.onProgress(80); 

只是一些例子,不是很多,但我希望帮助。

0

使用此

 class DownloadFileAsync extends AsyncTask<String, String, String> { 

@SuppressWarnings("deprecation") 
@Override 
protected void onPreExecute() { 
    super.onPreExecute(); 

    showDialog(DIALOG_DOWNLOAD_PROGRESS); 
} 

@Override 
protected String doInBackground(String... aurl) { 
    int count; 
    File root = android.os.Environment.getExternalStorageDirectory();    
    // 
    File dir = new File (root.getAbsolutePath()+"/downoad"); //make ur folder to put download 
    if(dir.exists()==false) { 
      dir.mkdirs(); 
     } 
    File file = new File(dir, "enter file name"); 
     try { 

       URL url = new URL(aurl[0]); 
       URLConnection conexion = url.openConnection(); 
       conexion.connect(); 

       int lenghtOfFile = conexion.getContentLength(); 
       Log.d("ANDRO_ASYNC", "Lenght of file: " + lenghtOfFile); 

       InputStream input = new BufferedInputStream(url.openStream()); 
       OutputStream output = new FileOutputStream(file); 

       byte data[] = new byte[1024]; 

       long total = 0; 

       while ((count = input.read(data)) != -1) 
        { 
         total += count; 
         publishProgress(""+(int)((total*100)/lenghtOfFile)); 
         output.write(data, 0, count); 
        } 

       output.flush(); 
       output.close(); 
       input.close(); 
     } catch (Exception e) {} 
     return null; 

} 

protected void onProgressUpdate(String... progress) { 
    Log.d("ANDRO_ASYNC",progress[0]); 
    mProgressDialog.setProgress(Integer.parseInt(progress[0])); 
} 

@SuppressWarnings("deprecation") 
@Override 
protected void onPostExecute(String unused) { 
    dismissDialog(DIALOG_DOWNLOAD_PROGRESS); 
    Toast.makeText(DisplayActivity.this,"Successfully downloaded in phone memory.", Toast.LENGTH_SHORT).show(); 
} 
    } 

怎么称呼?

new DownloadFileAsync().execute("your URL");