Android 异步任务不';t使用publishprogress更新进度对话框

Android 异步任务不';t使用publishprogress更新进度对话框,android,android-asynctask,Android,Android Asynctask,我有一个AsyncTask,它下载图像,并显示进度对话框。asynctask运行得非常好,图像下载的进度也正确地显示了值。我通过在doInBackground()中记录下载的值来检查它,然后使用publishProgress()。但是这个publishProgress不会增加progressdialog的栏 下面是我正在使用的代码 public class SingleMenuItemActivity extends Activity { public static final String K

我有一个AsyncTask,它下载图像,并显示进度对话框。asynctask运行得非常好,图像下载的进度也正确地显示了值。我通过在doInBackground()中记录下载的值来检查它,然后使用publishProgress()。但是这个publishProgress不会增加progressdialog的栏

下面是我正在使用的代码

public class SingleMenuItemActivity extends Activity {
public static final String KEY_TITLE = "title";
public static final String KEY_LINK = "link";
public static final String KEY_DATE = "date";

public static final String TAG = "SingleMenuItemActivity";
private ProgressDialog pDialog;
// Progress dialog type (0 - for Horizontal progress bar)
public static final int PROGRESS_BAR_TYPE = 0;

//public static ImageDownloadTask imTask;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.single_list_item);

    // getting intent data
    Intent in = getIntent();

    // Get XML values from previous intent
    String name = in.getStringExtra(KEY_TITLE);
    String pLink = in.getStringExtra(KEY_LINK);
    String pDate = in.getStringExtra(KEY_DATE);

    // Displaying all values on the screen
    TextView lblTitle = (TextView) findViewById(R.id.title_label);
    TextView lblDate = (TextView) findViewById(R.id.publish_label);
    lblTitle.setText(name);
    lblDate.setText(pDate);

// Set Image
    try {
        URL url = new URL(pLink);
        new ImageDownloadTask().execute(url);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

/**
 * Showing Dialog
 * */
@Override
protected Dialog onCreateDialog(int id) {
    switch (id) {
    case PROGRESS_BAR_TYPE: // we set this to 0
        pDialog = new ProgressDialog(this);
        pDialog.setMessage("Downloading image. Please wait...");
        pDialog.setIndeterminate(false);
        pDialog.setMax(100);
        pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        pDialog.setCancelable(false);
        pDialog.show();
        return pDialog;
    default:
        return null;
    }
}

class ImageDownloadTask extends AsyncTask<URL, Float, String> {

    public static final String TAG = "ImageDownloadTask";        
     ImageView imageView = (ImageView) findViewById(R.id.single_list_imageview);
     int count;
    @Override
    protected String doInBackground(URL... params) {
         try {

                URL url = params[0];
                URLConnection conection = url.openConnection();
                conection.connect();
                // this will be useful so that you can show a tipical 0-100% progress bar
                int lenghtOfFile = conection.getContentLength();

                // download the file
                InputStream input = new BufferedInputStream(url.openStream(), 8192);

                // Output stream
                OutputStream output = new FileOutputStream("/sdcard/downloadedfile.jpg");

                byte data[] = new byte[1024];

                long total = 0;

                while ((count = input.read(data)) != -1) {
                    total += count;
                    float pValue = (float)((total*100)/lenghtOfFile);
                    Log.d(TAG,"Download so far : "+pValue);
                    // publishing the progress....
                    // After this onProgressUpdate will be called
                    publishProgress(pValue);

                    // writing data to file
                    output.write(data, 0, count);
                }

                // flushing output
                output.flush();

                // closing streams
                output.close();
                input.close();

            } catch (Exception e) {
                Log.e("Error: ", e.getMessage());
            }
        return null;
    }


    @Override
    protected void onPostExecute(String result) {

        Log.d(TAG,"Bitmap download complete");
        dismissDialog(PROGRESS_BAR_TYPE);

        // Displaying downloaded image into image view
        // Reading image path from sdcard
        String imagePath = Environment.getExternalStorageDirectory().toString() + "/downloadedfile.jpg";
        // setting downloaded into image view
        imageView.setImageDrawable(Drawable.createFromPath(imagePath));
    }

    @Override
    protected void onCancelled(){
        Log.d(TAG,"Progress Dialog was Cancelled");
        pDialog.dismiss();
    }

    @Override
    protected void onPreExecute() {
         super.onPreExecute();
        // Things to be done before execution of long running operation. For
        // example showing ProgessDialog
         showDialog(PROGRESS_BAR_TYPE);
    }

    protected void onProgressUpdate(Integer... values) {
        //super.onProgressUpdate(values);
        Log.d(TAG,"values"+values[0]);
//          incrementProgressBy(values[0]);
        //pDialog.setProgress(values[0]);
        setProgress(values[0]);
        }
    }
}
公共类SingleMenuItemActivity扩展活动{
公共静态最终字符串键\u TITLE=“TITLE”;
公共静态最终字符串键\u LINK=“LINK”;
公共静态最终字符串键\u DATE=“DATE”;
公共静态最终字符串标记=“SingleMenuItemActivity”;
私人对话;
//进度对话框类型(0-用于水平进度条)
公共静态最终整数进度条类型=0;
//公共静态图像下载任务imTask;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.single_list_项);
//获取意图数据
Intent in=getIntent();
//从以前的意图中获取XML值
字符串名称=in.getStringExtra(关键字标题);
字符串pLink=in.getStringExtra(键链接);
字符串pDate=in.getStringExtra(键日期);
//在屏幕上显示所有值
TextView lblTitle=(TextView)findViewById(R.id.title_标签);
TextView lblDate=(TextView)findViewById(R.id.publish_标签);
lblTitle.setText(名称);
lblDate.setText(pDate);
//设置图像
试一试{
URL=新URL(pLink);
新建ImageDownloadTask().execute(url);
}捕获(IOE异常){
e、 printStackTrace();
}
}
/**
*显示对话框
* */
@凌驾
受保护的对话框onCreateDialog(int id){
开关(id){
案例进度条类型://我们将其设置为0
pDialog=新建进度对话框(此对话框);
setMessage(“正在下载图像,请稍候…”);
pDialog.setUndeterminate(假);
pDialog.setMax(100);
pDialog.setProgressStyle(ProgressDialog.STYLE_水平);
pDialog.setCancelable(假);
pDialog.show();
返回pDialog;
违约:
返回null;
}
}
类ImageDownloadTask扩展了AsyncTask{
公共静态最终字符串标记=“ImageDownloadTask”;
ImageView ImageView=(ImageView)findViewById(R.id.single\u list\u ImageView);
整数计数;
@凌驾
受保护的字符串doInBackground(URL…参数){
试一试{
URL=参数[0];
URLConnection conconnection=url.openConnection();
conconnect.connect();
//这将非常有用,以便您可以显示典型的0-100%进度条
int lenghtOfFile=conconnect.getContentLength();
//下载该文件
InputStream输入=新的BufferedInputStream(url.openStream(),8192);
//输出流
OutputStream output=新文件OutputStream(“/sdcard/downloaddedfile.jpg”);
字节数据[]=新字节[1024];
长总计=0;
而((计数=输入。读取(数据))!=-1){
总数+=计数;
浮点值=(浮点值)((总计*100)/长度浮点值);
Log.d(标记“下载到目前为止:”+pValue);
//发布进度。。。。
//在此之后,将调用onProgressUpdate
出版进度(pValue);
//将数据写入文件
输出.写入(数据,0,计数);
}
//冲洗输出
output.flush();
//合流
output.close();
input.close();
}捕获(例外e){
Log.e(“错误:,e.getMessage());
}
返回null;
}
@凌驾
受保护的void onPostExecute(字符串结果){
Log.d(标记“位图下载完成”);
解雇对话框(进度条类型);
//在图像视图中显示下载的图像
//从SD卡读取图像路径
字符串imagePath=Environment.getExternalStorageDirectory().toString()+“/downloadedfile.jpg”;
//设置已下载到图像视图中
setImageDrawable(Drawable.createFromPath(imagePath));
}
@凌驾
受保护的void onCancelled(){
Log.d(标记“进度对话框被取消”);
pDialog.disclose();
}
@凌驾
受保护的void onPreExecute(){
super.onPreExecute();
//在执行长时间运行的操作之前要做的事情
//显示ProgesDialog的示例
显示对话框(进度条类型);
}
受保护的void onProgressUpdate(整型…值){
//super.onProgressUpdate(值);
Log.d(标记“值”+值[0]);
//递增进度(值[0]);
//pDialog.setProgress(值[0]);
setProgress(值[0]);
}
}
}
请告诉我哪里做错了


谢谢,

问题是
异步任务的进度类型定义为
Float
,而
onProgressUpdate()
方法将
Integer
作为参数类型。通过这种方式声明
onProgressUpdate()
,您将重载标准回调方法,而
异步任务将不会调用它。如果向此方法添加
@Override
注释,代码也将无法编译。因此,您应该将
onProgressUpdate()
的参数类型更改为
Float
,或者将
AsyncTask
的进度类型更改为
Integer
,这是一个更好的解决方案,因为
ProgressDialog的
setProgress()
int
作为参数类型

问题是
AsyncTask
的进度类型被定义为
Float