我如何在后台WebView(Android)中下载URL?

时间:2013-09-01 19:03:13

标签: android android-webview

我想显示启动画面,并在此时下载WebView中的网址。 SplashView是我以编程方式创建的资产的gif

public class GIFView extends View {
private Movie mMovie;
private long mMoviestart;

public GIFView(Context context, InputStream stream) {
    super(context);        
    mMovie = Movie.decodeStream(stream); 
}
@Override 
protected void onDraw(Canvas canvas) { 
    canvas.drawColor(Color.TRANSPARENT); 
    super.onDraw(canvas); 
    final long now = SystemClock.uptimeMillis(); 
    if (mMoviestart == 0) { 
        mMoviestart = now; 
    } 
    final int relTime = (int)((now - mMoviestart) % mMovie.duration()); 
    mMovie.setTime(relTime); 
    mMovie.draw(canvas, 0, 0); 
    this.invalidate(); 
}
}

其中stream是

try {
        String path = this.getApplicationContext().getResources().getString(R.string.subpath) + 
                      "/vsplesk.gif";
        mStream = getAssets().open(path);
    } 
    catch (IOException e) {
        e.printStackTrace();
    }

我怎么能这样做?也许有人已经决定了同样的任务。提前谢谢

1 个答案:

答案 0 :(得分:1)

您可以通过创建asynctask类来尝试这样做

它将在后台运行然后你告诉它在后台加载/下载后该做什么。

 private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
     protected Long doInBackground(URL... urls) {
         int count = urls.length;
         long totalSize = 0;
         for (int i = 0; i < count; i++) {
             totalSize += Downloader.downloadFile(urls[i]);
             publishProgress((int) ((i / (float) count) * 100));
             // Escape early if cancel() is called
             if (isCancelled()) break;
         }
         return totalSize;
     }

     protected void onProgressUpdate(Integer... progress) {
         setProgressPercent(progress[0]);
     }

     protected void onPostExecute(Long result) {
         showDialog("Downloaded " + result + " bytes");
     }
 }

Asynctask - Android developers