2013-02-04 3 views
0

asynctask가 실행되기 전에 연결과 올바른 연결을 확인하지만 때로는 응용 프로그램이 다운되는 경우가 있습니다. UI 스레드에서 생각하기 때문입니다. AsyncTask에 코드를 추가하면 응용 프로그램이 항상 중단됩니다. 어떤 해결책? 에서 onCreate 방법에AsyncTask의 연결 확인

:

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

귀하의 질문은 매우 모호합니다!

그러나 :

con = (HttpURLConnection) url.openConnection(); 

그렇게 간단한 솔루션은 새로운 Thread 내에서 모든 것을 추가하는 것입니다 : 새로운 안드로이드에서, 당신은 UI 스레드에서이 줄을 실행할 수 없습니다

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

그러나

//show alertdialog with the problem 
notConnection(); 

이 FUNC : 당신의 코드는 다음과 같은 대화 상자 (추측)을 보여주기 위해 일부 블록을 가지고 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 
        } 

    } 
}