Android应用程序在循环中显示空白屏幕(不更新UI)

时间:2013-06-07 07:43:29

标签: android

在我的应用程序中,客户端连接到服务器。它等待直到与服务器的连接发生。在此期间,应用程序没有响应。我怎么解决这个问题。尝试的代码段显示在下面

public Connection(){
    client.SetParent(this);
    this.context = g.getContext();
    bConnected = false;

    mNetworkRunner = new Runnable() {
        public void run() {
            try {
                Log.e("", "mNetworkRunner...");

                if( SendKeepAlive()){
                    Main.conStatus(1);
                    Log.e("", "SendKeepAlive...");
                }
                else {
                    Main.conStatus(0);
                    Log.e("", "No connection...");

                    g.log("Connection to server is lost... Trying to Connect...");
                    while(true){
                        Log.e("", "In while loop...");

                        if(!Connect()){
                            g.log("Trying...");
                            Log.e("", "In Connect no connect...");
                            Thread.sleep(2000);
                        }
                        else {
                            g.log("Connected");
                            break;
                        }

                    }
                    Main.conStatus(1);
                }
                mNetworkHandler.postDelayed(this, 30000);
            }
            catch (Exception e) {
                e.printStackTrace();
            }
        }
    };      

}
// 
private void CheckNetworkConnection(){
    if( mNetworkHandler == null ){
        mNetworkHandler = new Handler();
        mNetworkHandler.post(mNetworkRunner);
        Log.e("", "CheckNetworkConnection...");
    }       
}

2 个答案:

答案 0 :(得分:2)

你在UI线程中花费了大量的时间来创建问题。在这种情况下,您应该使用AsyncTask。

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

 private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
     protected Long doInBackground(URL... urls) {

    //do your time consuming task here
     }

     protected void onProgressUpdate(Integer... progress) {
         //setProgressPercent(progress[0]);
     }

     protected void onPostExecute(Long result) {
         //showDialog("Downloaded " + result + " bytes");
     }
 }

创建后,任务执行非常简单:

 new DownloadFilesTask().execute(url1, url2, url3);

答案 1 :(得分:1)

mNetworkHandler = new Handler()会在UI线程上执行Runnable,你需要HandlerThread

private void CheckNetworkConnection(){
    if( mNetworkHandler == null ){
        HandlerThread handlerThread = new HandlerThread("thread");
        handlerThread.start();
        mNetworkHandler =  new Handler(handlerThread.getLooper());
        mNetworkHandler.post(mNetworkRunner);
        Log.e("", "CheckNetworkConnection...");
    }
}