ProgressDialog如果没有Internet连接,则关闭AlertDialog

时间:2012-06-02 16:56:46

标签: android progressdialog android-alertdialog internet-connection

我正在为我的应用程序使用Web服务。数据在callWebService()方法中很胖。我在填充ListView时显示ProgressDialog。我也想检查是否有网络连接来关闭ProgressDialog并且向用户显示AlertDialog。有人可以帮我这里是我的代码

     myProgressDialog = ProgressDialog.show(ExchangeMoneMK1Activity.this,
                     "Please wait...", "Loading...", true);
         Thread thread = new Thread(this);
         thread.start();


 private boolean isNetworkAvailable() {
    ConnectivityManager connectivityManager 
          = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
    return activeNetworkInfo != null;
}




private Handler handler = new Handler() {
    @Override
    public void handleMessage(Message msg) {
        switch(msg.what){
        case 0:

            myProgressDialog.dismiss();
            int resID = R.layout.list_item;
            aa = new ExchangeRateAdapter(ExchangeMoneMK1Activity.this, resID,currencyList);

            lw.setAdapter(aa);
            break;
        }


    }

};

public void run() {
    // TODO Auto-generated method stub

    try {
        if(isNetworkAvailable())
        callWebService();
        handler.sendEmptyMessage(0);
    }


     catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (XmlPullParserException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (ParserConfigurationException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

我还没有alertdialog,因为如果没有互联网连接,进度条不会被解雇 我已经放入AndroidManifest特权了

有人能帮助我吗?

2 个答案:

答案 0 :(得分:0)

最后也使用try catch并放入handler.sendEmptyMessage(0);在finnaly ...

因为我认为你得到任何一个excption并且你的flow跳转到catchWebService().....并且没有到达handler.sendEmptyMessage(0);线........

答案 1 :(得分:0)

使用AsyncTask。它会简单得多。一般模式如下。可能会有一些小的编译错误,但是,这会给你一个想法。

class MyTask extends AsyncTask<Void, Void, ArrayList> {
    protected Void doInBackground(Void... params) {
        ArrayList currencyList;
        if(isNetworkAvailable())
            currencyList = callWebService();
        return currencyList;
    }
    void onPreExecute() {
        myProgressDialog = ProgressDialog.show(ExchangeMoneMK1Activity.this,
                 "Please wait...", "Loading...", true);
    }
    void onPostExecute(ArrayList currencyList) {
        myProgressDialog.dismiss();
        if (currencyList == null) {
            //Handle error
            return;
        }
        int resID = R.layout.list_item;
        aa = new ExchangeRateAdapter(ExchangeMoneMK1Activity.this, resID,currencyList);

        lw.setAdapter(aa);
    }
}