Android错误:通知用户正在下载的文件

时间:2012-03-05 03:20:56

标签: android android-asynctask download

我有一个从网址下载视频的代码。我正在使用AsyncTask。现在,我想要做的是通过进度对话框通知用户正在下载的视频,或类似“下载视频2的10”。我使用以下代码:

//DOWNLOAD VIDEOS
private class downloadVideosAsync extends AsyncTask <String, String, String>{

    protected void onPreExecute(){
        super.onPreExecute();
        MyActivity.this.mProgressDialog.setMessage("Downloading Videos...");
    }

    @Override
    protected String doInBackground(String... strings){
        try{

            ArrayList<String> VideoNames = VideosM.getVideoNames();
            ArrayList<String> VideoUrls = VideosM.getVideoUrls();

            File vidFile = null;
            int videoNamesLenght = VideoNames.size();
            int x;

            for(x = 0; x < videoNamesLenght; x++) {

                //download video
                String[] videoName = VideoNames.get(x).split("/");
                String currentFile = videoName[0] + "." + videoName[1];
                String currentFileURL = VideoUrls.get(x) + VideoNames.get(x);

                vidFile = new File(Environment.getExternalStorageDirectory() 
                                    + "/Engagia/Downloads/Videos/", currentFile);

                if( !vidFile.exists() ){
                    int curr_vid = x + 1;

                    String ui_msg = "Downloading Videos " + curr_vid + " of " + videoNamesLenght + "...";
                    MyActivity.this.mProgressDialog.setMessage( ui_msg );

                    VideosC.downloadVideoFile(currentFile, currentFileURL, vidFile);

                }
            }

        }catch (NullPointerException e){
            Log.e(LOG_TAG, e.toString());
        }catch(Exception e){
            Log.e(LOG_TAG, e.toString());
        }
        return null;
    }

    @Override
    protected void onPostExecute(String lenghtOfFile) {
        new downloadSlideshowsAsync().execute();
    }
}

上面的代码给我一个错误:

android.view.ViewRoot $ CalledFromWrongThreadException:只有创建视图层次结构的原始线程才能触及其视图。

编辑:

我也尝试过:

runOnUiThread(new Runnable() {
     public void run() {

        String ui_msg = "Downloading Videos " + curr_vid + " of " + videoNamesLenght + "...";
        Engagia.this.mProgressDialog.setMessage( ui_msg );
        Log.v("VideosController.java", ui_msg );

    }
});

但给了我同样的错误......

2 个答案:

答案 0 :(得分:2)

只有一个特殊的线程(通常称为“UI线程”)才能修改UI元素。您可以通过运行runOnUiThread函数Activity class中的内容来在UI线程上运行特定代码。例如:

runOnUiThread(new Runnable() {
    public void run() {
    // ...
    }
});

答案 1 :(得分:2)

使用onProgreesUpdate更新进度条。

在Android开发者网站link

上找到详细信息