2013-02-04 36 views
0

我檢查連接和asynctask之前的正確鏈接,但有時應用程序崩潰,因爲我認爲在UI線程上執行它。如果我把代碼放在AsyncTask上,應用程序總是崩潰。任何解決方案檢查AsyncTask上的連接

在onCreate方法:

if(connectionOK()) 
     { 
      try { 
       url = new URL(bundle.getString("direccion")); 
       con = (HttpURLConnection) url.openConnection(); 
       if(con.getResponseCode() == HttpURLConnection.HTTP_OK) 
       { 
        Tarea tarea = new Tarea(this); 
        tarea.execute(); 
       } 
       else 
       { 
        con.disconnect(); 
        //show alertdialog with the problem 
        direccionInvalida(); 
       } 
     } catch (Exception e){e.printStackTrace();} 

     } 
     else 
     { 
      //show alertdialog with the problem 
      notConnection() 
     } 
+0

你可以發佈你的AsyncTask嗎?你在哪裏檢查連接? –

+0

可以顯示你的logcat/stacktrace的錯誤嗎? –

回答

0

你的問題很模糊!

然而:在新的機器人,你可以不執行UI線程上這一行:

con = (HttpURLConnection) url.openConnection(); 

這麼一個簡單的解決辦法是增加一個新的線程中的一切:

new Thread() { 
    public void run() { 
     //add all your code 
    } 
}.start(); 

然而,你的代碼有一些塊顯示對話框(猜測)是這樣的:

//show alertdialog with the problem 
notConnection(); 

這些函數應該在UI線程上完成。因此,使用一個處理程序:

//add this outsire the thread 
Handler mHandler = new Handler(); 

那麼你的代碼裏面使用:

mHandler.post(new Runnable() { 
    public void run() { 
     notConnection(); 
    } 
}); 

最後,這是一個修復。真正的解決方案將是你無論如何張貼AsyncTask並處理錯誤或成功在onPostExecute()

1

試試這個,檢查網絡連接doInBackground

public class GetTask extends AsyncTask<Void, Void, Integer> { 

    protected void onPreExecute() { 
     mProgressDialog = ProgressDialog.show(MainActivity.this, 
       "Loading", "Please wait"); 
    } 

    @Override 
    protected Integer doInBackground(Void... params) { 
     // TODO Auto-generated method stub 
        if(connectionOK()){ 
     //ADD YOUR API CALL 
       return 0; 
        }esle{ 
        return 1; 
        } 

    } 

    protected void onPostExecute(Integer result) { 
     super.onPostExecute(result); 
     if (mProgressDialog.isShowing()) { 
      mProgressDialog.dismiss(); 
     } 
        if(result == 0){ 
         //do your stuff 
        }else{ 
         //show alertdialog with the problem 
        } 

    } 
}