0

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

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...");
    }       
}
4

2 回答 2

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);
于 2013-06-07T08:26:51.130 回答
1

mNetworkHandler = new Handler() 将使 Runnable 在 UI Thread 上执行,您需要 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...");
    }
}
于 2013-06-07T07:47:43.233 回答