调用Web服务或任何网络呼叫时应用程序挂起

时间:2012-10-05 11:42:51

标签: android android-intent

在Android应用程序中,当我启动活动时,它显示黑屏或应用程序挂起几秒钟。我想要黑屏我要显示进度条。我尝试了很多次但是不能这样做。

String xml = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>" 
                + "<category><Id>" + catId + "</Id></category>";
StringBuilder resXML = new Connection().getResponseString("http://192.168.1.14/virtualMirror/productlisting.php", xml); // TODO URL change
if(!resXML.equals("")) {
    XMLParser parser = new XMLParser();
    Document doc = parser.getDomElement(resXML.toString()); // getting DOM element
    NodeList nodeList = doc.getElementsByTagName("Product");

    Intent intent = new Intent(this, ProductListing.class);
    Bundle bundle = new Bundle();
    bundle.putLong("CategoryId", catId);
    bundle.putString("CategoryName", catName);
    intent.putExtras(bundle);
    startActivity(intent);
}

2 个答案:

答案 0 :(得分:1)

使用 AsyncTask。

AsyncTask可以正确,轻松地使用UI线程。该类允许执行后台操作并在UI线程上发布结果,而无需操纵线程和/或处理程序。

AsyncTask执行另一个线程内doInBackground()内的所有内容,该线程无权访问您的视图所在的GUI。

preExecute()postExecute()使您可以在此新线程中发生繁重操作之前和之后访问GUI,您甚至可以将long操作的结果传递给postExecute(),然后显示任何结果处理。

class LoadCategory extends AsyncTask<Void, Void, Void> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        Pd = new ProgressDialog(getApplicationContext());
        Pd.show();
    }

    @Override
    protected Void doInBackground(Void... params) {
        String xml = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>"
                + "<category><Id>" + catId + "</Id></category>";

        StringBuilder resXML = new Connection().getResponseString("http://192.168.1.14/virtualMirror/productlisting.php",xml); // TODO URL change
        if (!resXML.equals("")) {
            XMLParser parser = new XMLParser();
            Document doc = parser.getDomElement(resXML.toString());
            NodeList nodeList = doc.getElementsByTagName("Product");
            return null;
        }
    }

    @Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);
        Pd.dismiss();
        Intent intent = new Intent(this, ProductListing.class);
        Bundle bundle = new Bundle();
        bundle.putLong("CategoryId", catId);
        bundle.putString("CategoryName", catName);
        intent.putExtras(bundle);
        startActivity(intent);
    }
}

并在onCreate()方法中使用此课程。

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    new LoadCategory().execute();
}

答案 1 :(得分:0)

您应首先使用进度条加载屏幕,然后使用新线程调用此代码。为此,您可以创建一个扩展线程类的新类并覆盖run方法。您必须使用这些消息来获取已加载值的通知。

这是一个快速而肮脏的例子,但希望足以让你理解整体流程。

private final Handler handler = new Handler(){
        public void handleMessage(Message msg)
        {
            int total = msg.getData().getInt("total");
            if (total <= 0)
            {
            //Handle the response here
            } 
        }
    };

    private class yourclassname extends Thread{
        Handler mHandler;
        String _serviceUrl;
        CarpoolCancellationLoader(Handler h,String serviceUrl)
        {
            mHandler = h;
            _serviceUrl = serviceUrl;

        }

        private class SerializableClassName 
        {
        ..Put your serializable data here
        }

        @Override
        public void run()
        {
            cancelResponse = runJSONParser();
            //Send the thread activity done message to the handler
            Message msg = mHandler.obtainMessage();
            Bundle b = new Bundle();
            b.putInt("total", -1);
            msg.setData(b);
            mHandler.sendMessage(msg);

        }

          public YourResponseType runJSONParser()
          {
              try
              {
                //Perform your loading operation here
              }
              catch(Exception ex)
            {
                throw ex;
            }
          }

          public String convertStreamToString(InputStream is)
          {
              BufferedReader reader = new BufferedReader(new InputStreamReader(is));
              StringBuilder sb = new StringBuilder();

              String line = null;

              try
              {
                  while ((line = reader.readLine()) != null)
                  {
                      sb.append(line + "\n");
                  }
              }
              catch (IOException e)
              {
                  e.printStackTrace();
              }
              finally
              {
                  try
                  {
                      is.close();
                  }
                  catch (IOException e)
                  {
                      e.printStackTrace();
                  }
              }

              return sb.toString();
          }
    }

这不是很干净的代码,但足以让您全面了解创建新线程的代码结构,并通过异步运行获得结果。