2013-04-10 43 views
2

當我在Android 2.3.6上運行這段代碼時,它工作正常。在4.0上,我得到一個StrictMode異常。從一些關於SO的問題來看,似乎你不能在UI線程上進行網絡操作。但我沒有在UI線程上進行任何UI操作。

我直接調用doBackground而不執行,因爲我需要檢查doBackground的返回值。我想下面應該工作。

我在這裏錯過了什麼?

handler.postDelayed(new Runnable() { 
@Override 
public void run() { 
    God.identityHash = (String) new SwitchServer((IActionBar) splashScreen, 
       God.mCruiseOnServer, nameText, phoneNumberText) 
       .doInBackground(null); 

    if (!mIsBackButtonPressed && God.identityHash != null) { 
     FlurryAgent.logEvent(God.TCACCEPTED_AND_REGISTERED); 
     Intent intent = new Intent(SplashScreen.this, HomeScreen.class); 
     SplashScreen.this.startActivity(intent); 
     finish(); 
    } else { 
     Toast.makeText(splashScreen, 
      "Unable to save your details. Please try again.", 
      Toast.LENGTH_LONG).show(); 
     God.setTermsAndConditions(splashScreen, false); 
    } 
} 
}, SPLASH_DURATION); 

編輯:手機上未啓用嚴格模式。

+0

是'AsyncTask'還是別的什麼,我真的不明白你想在這裏做什麼 – hardartcore 2013-04-10 08:57:36

+0

是的,我沒有在這個地方以「常規」方式使用AsyncTask。 – Siddharth 2013-04-10 08:59:20

+0

我建議你使用AsyncTask來實現你想要的東西。 – hardartcore 2013-04-10 09:45:22

回答

3

首先,StrictMode是您明確從代碼開啓的東西,它只是一種調試幫助,不應將其留在生產代碼中。

其次,手動調用.doInBackground意味着在UI線程上運行它。如果按照預期使用AsyncTask,則在.onPostExecute中獲取其返回值作爲參數。

+0

我在一個處理程序runnable,愚蠢的問題中調用doInBackground,但沒有把doInBackground關閉UI線程? – Siddharth 2013-04-10 08:59:00

+0

不,消息處理程序運行它(雖然延遲),這意味着UI線程。 – 2013-04-10 09:01:43