【问题标题】:android how to set time for progressdialogandroid如何设置进度对话框的时间
【发布时间】:2016-05-04 20:52:00
【问题描述】:

在我的应用程序中,我有一个 processDialog(使用 AsyncTask),并且在 doInbackground 它从服务器获取数据。 一切正常。 但我想如果互联网速度很慢,那么它会发出警告警报“你的互联网连接有问题” 所以为此我想知道progressDialog需要多少时间才能关闭。这样我就可以设置一个条件,如果时间 > 5imns,那么警报就会到来。

我如何知道需要多少时间或如何设置对话时间。

请任何人回答我。 提前谢谢你

下面是我的代码,

public class InfoActivity extends Activity {

private TextView tvRestroName, tvRestroAddr, tvRestroArea, tvRestroCity,
        tvRestroPhone, tvRestroRating, tvRestroCuisines, tvRestroAttr;
private ImageView imgRestro;
private ImageAdapter coverImageAdapter = new ImageAdapter(this);
private ScrollView sv;
static Bitmap restroBitmap, selectedImage;

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);

    // This activity has two different views so to bind two views
    // LinearLayout is used here
    // from two views one is xml and another is coverflow class
    LinearLayout ll = new LinearLayout(this);
    ll.setOrientation(LinearLayout.VERTICAL);
    LayoutInflater inflater = (LayoutInflater) this
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View view = inflater.inflate(R.layout.info, null);

    // adding one view as xml
    ll.addView(view);

    CoverFlow coverFlow;
    coverFlow = new CoverFlow(this);
    coverFlow.setAdapter(new ImageAdapter(this));
    // set Imageadapter which is define within InfoActivity class
    coverFlow.setAdapter(coverImageAdapter);

    coverFlow.setSpacing(-25);
    coverFlow.setSelection(4, true);
    coverFlow.setAnimationDuration(1000);
    // and another view as class
    ll.addView(coverFlow);
    sv = new ScrollView(this);
    sv.addView(ll);

    // To add all views to InfoActivity
    setContentView(sv);
    // to initialize all variables like textview and imageview
    setupViews();
    // for progress dialog
    new DownloadTask().execute(this);

    // click event of images within imageadapter
    coverFlow.setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(AdapterView<?> arg0, View arg1,
                int position, long arg3) {
            Toast.makeText(InfoActivity.this, "" + (position + 1),
                    Toast.LENGTH_SHORT).show();
            // imageView.setImageResource(mImageIds[arg2]);
            String slImg = TabHostActivity.galleryArray[position]; 
            selectedImage = loadBitmap(slImg);
            Intent i = new Intent(InfoActivity.this,
                    PostCommentActivity.class);
            startActivity(i);

        }
    });
}

// to initialize all variables like textview and imageview
private void setupViews() {
    imgRestro = (ImageView) findViewById(R.id.imageResturant);
    tvRestroName = (TextView) findViewById(R.id.tvRestroName);
    tvRestroAddr = (TextView) findViewById(R.id.tvRestroAddr);
    tvRestroArea = (TextView) findViewById(R.id.tvRestroArea);
    tvRestroCity = (TextView) findViewById(R.id.tvRestroCity);
    tvRestroPhone = (TextView) findViewById(R.id.tvRestroPhone);
    tvRestroRating = (TextView) findViewById(R.id.tvRestroRating);
    tvRestroCuisines = (TextView) findViewById(R.id.tvRestroCuisines);
    tvRestroAttr = (TextView) findViewById(R.id.tvRestroAttributes);
}

// set values to all fields
private void setupValues() {
    tvRestroName.setText("Restaurant " + TabHostActivity.restroName);
    //Bitmap bmp = loadBitmap(TabHostActivity.restroImageurl);
    System.out.println("str ;" + TabHostActivity.restroImageurl);

    imgRestro.setImageBitmap(Bitmap.createScaledBitmap(restroBitmap, 300, 300, true));
    System.out.println("Image seted");
    tvRestroAddr.setText("Address: " + TabHostActivity.addr);
    tvRestroArea.setText("Area: " + TabHostActivity.area);
    tvRestroCity.setText("City:" + TabHostActivity.city);

    String phones = "Phones: ";
    for (int i = 0; i < TabHostActivity.phoneArray.length; i++)
        phones += TabHostActivity.phoneArray[i] + ", ";
    tvRestroPhone.setText(phones.substring(0, phones.length() - 2));

    tvRestroRating.setText("Rating: " + TabHostActivity.rating);

    String cuisines = "Cuisines: ";
    for (int i = 0; i < TabHostActivity.cuisinesArray.length; i++)
        cuisines += TabHostActivity.cuisinesArray[i] + ", ";
    tvRestroCuisines.setText(cuisines.substring(0, cuisines.length() - 2));

    String attr = "Attributes: ";
    for (int i = 0; i < TabHostActivity.attributesArray.length; i++)
        attr += TabHostActivity.attributesArray[i] + ", ";
    tvRestroAttr.setText(attr.substring(0, attr.length() - 2));
}

// to get image from url in form of bitmap
private static Bitmap loadBitmap(String url) {
    URL myFileUrl = null;
    InputStream is = null;
    try {
        myFileUrl = new URL(url);
    } catch (MalformedURLException e) {
        e.printStackTrace();
    }
    try {
        HttpURLConnection conn = (HttpURLConnection) myFileUrl
                .openConnection();
        conn.setDoInput(true);
        conn.connect();
        is = conn.getInputStream();
        Log.i("i m connected", "Download in info for main image");

    } catch (IOException e) {
        e.printStackTrace();
    }
    Log.i("i m connected", "Download in info for main image");
    return BitmapFactory.decodeStream(is);
}

// for progressdialog
private class DownloadTask extends AsyncTask<Context, Integer, Void> {

    private ProgressDialog Dialog = new ProgressDialog(InfoActivity.this);

    @Override
    protected void onPreExecute() {
        System.out.println("In onPreExecute ");
        Dialog.setTitle("Loading");
        Dialog.setMessage("Please wait for few seconds...");
        //Dialog.setMax(100);
        //Dialog.setProgress(0);
        Dialog.show();

    }

    @Override
    protected Void doInBackground(Context... params) {
        System.out.println("In doInBackground ");
        //examineJSONFile();
        restroBitmap= loadBitmap(TabHostActivity.restroImageurl);
        System.out.println("conversion of bitmap done");
        int i = 0;

        System.out.println("In doInBackground ");
        Dialog.dismiss();
        //Dialog.cancel();
        for (i = 0; i < 10; i++)
            System.out.println("In doInBackground " + i);

        Bitmap bitmap = null;
        for (i = 0; i < TabHostActivity.galleryArray.length; i++) {
            try {
                publishProgress(i);

            } catch (Exception e) {
                Log.i("in while", e.getMessage());
            }

            bitmap = loadBitmap(TabHostActivity.galleryArray[i]);
            TabHostActivity.bitmapHash.remove(TabHostActivity.galleryArray[i]);
            TabHostActivity.bitmapHash.put(TabHostActivity.galleryArray[i], bitmap);

        }
        return null;
    }

    @Override
    protected void onProgressUpdate(Integer... progress) {
        if (progress[0]==0) {
            setupValues();
            System.out.println("setupvalues");
        } else {
            System.out.println("In progress ");
            coverImageAdapter.setnotify();
        }
    }

    @Override
    protected void onPostExecute(Void arg) {
        System.out.println("In onPostExecute ");
        }
}

public class ImageAdapter extends BaseAdapter {
    int mGalleryItemBackground;
    private Context mContext;
    private BitmapDrawable drawable;
    private FileInputStream fis;

    public ImageAdapter(Context c) {
        mContext = c;
        }

    public int getCount() {
        return TabHostActivity.galleryArray.length;
    }

    public Object getItem(int position) {
        return position;
    }

    public long getItemId(int position) {
        return position;
    }

    public void setnotify() {
        notifyDataSetChanged();
    }

    public View getView(int position, View convertView, ViewGroup parent) {
        ImageView i = new ImageView(mContext);
        fetchDummy(TabHostActivity.galleryArray[position], i);
        i.setLayoutParams(new CoverFlow.LayoutParams(200, 200));
        i.setScaleType(ImageView.ScaleType.CENTER_INSIDE);

        // Make sure we set anti-aliasing otherwise we get jaggies
        drawable = (BitmapDrawable) i.getDrawable();
        try {
            drawable.setAntiAlias(true);
        } catch (Exception e) {
            System.out.println("Exception in getview :" + e);
        }

        return i;

        // return mImages[position];
    }

    /**
     * Returns the size (0.0f to 1.0f) of the views depending on the
     * 'offset' to the center.
     */
    public float getScale(boolean focused, int offset) {
        /* Formula: 1 / (2 ^ offset) */
        return Math.max(1, 2.0f / (float) Math.pow(2, Math.abs(offset)));
    }

    private void fetchDummy(String urlString, ImageView i) {
        if (TabHostActivity.bitmapHash.containsKey(urlString)) {
            i.setImageBitmap(TabHostActivity.bitmapHash.get(urlString));
        }
    }

}

【问题讨论】:

标签: android


【解决方案1】:

只需跟踪创建异步任务时的开始时间(在类创建中或在onPreExecute() 中)。然后每个onProgressUpdate() 检查发生了多长时间,并执行适当的超时逻辑。

如果您只使用简单的微调对话框来获取进度而不调用onProgressUpdate(),那么您将不得不重新设计您的 doInBackground 以定期调用它,因为您只能在onProgressUpdate() 中显示 UI 更改而不是在后台线程中。

编辑:对您上传的代码的评论。

使用BitmapFactory.decodeStream(is) 意味着您无法轻松检查互联网速度。

您可以更改此设置以在读取循环中将流加载到byte[] 中,并监控它在那里花费的时间,然后如果运行速度太慢,则向donInBackground() 方法抛出超时异常。然后doInBackground() 可以捕获异常,将适当的代码返回给onPostExecute()

onPostExecute() 需要接受一个 int 参数,并决定在那里做什么,例如如果您传递一个代码 0,它可以假设一切正常,并关闭对话框。如果它得到 1,则假设发生超时并关闭对话框,然后显示“您的连接超时”消息。

粗略地说,代码是(我还没有尝试过):

        // ...
        conn.setDoInput(true);
        conn.connect();
        is = conn.getInputStream();
        Log.i("i m connected", "Download in info for main image");

    } catch (IOException e) {
        e.printStackTrace();
    }

    Log.i("i m connected", "Download in info for main image");

    // read the InputStream into an array
    long startTime = System.currentTimeMillis();
    ByteArrayOutputStream buffer = new ByteArrayOutputStream();
    int nRead;
    byte[] data = new byte[16384];

    while ((nRead = is.read(data, 0, data.length)) != -1) {
      buffer.write(data, 0, nRead);
      if ((System.currentTimeMillis() - startTime) > 60000) {
          is.close();
          throw new MyTimeoutException();
      }
    }
    return BitmapFactory.decodeByteArray(buffer.toByteArray());
}

@Override
protected Integer doInBackground(Context... params) {
    // ...

    Bitmap bitmap = null;
    for (i = 0; i < TabHostActivity.galleryArray.length; i++) {
        try {
            publishProgress(i);

        } catch (Exception e) {
            Log.i("in while", e.getMessage());
        }

        try {
            bitmap = loadBitmap(TabHostActivity.galleryArray[i]);
        } catch (MyTimeoutException e) {
            return RESULT_TIMEOUT;
        }
        TabHostActivity.bitmapHash.remove(TabHostActivity.galleryArray[i]);
        TabHostActivity.bitmapHash.put(TabHostActivity.galleryArray[i], bitmap);

    }
    return RESULT_OK;
}

@Override
protected void onPostExecute(Integer resultCode) {
    if (resultCode == RESULT_OK) {
        // ... things were good, close dialog etc
    } else {
        // ... close spinner and show a "timeout" dialog
    }
}

【讨论】:

  • 只需检查我的代码并告诉我应该在这里做什么?谢谢
  • 正如在您更新的代码中,您正在检查时间限制 1 分钟。没关系,但我希望在这种情况下超过 1 分钟,然后对话框也会关闭,并且应该发出警告。我如何在该条件下关闭对话框
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-21
  • 2013-03-18
  • 2019-04-30
相关资源
最近更新 更多