當我嘗試運行此代碼,它給我的這個錯誤android.os.NetworkOnMainThreadException
下面是完整的代碼:異常android.os.NetworkOnMainThreadException
final EditText editText = (EditText) findViewById(R.id.ed);
Button buttonX = (Button) findViewById(R.id.ok);
buttonX.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
final String message = editText.getText().toString();
new Thread() {
public void run() {
Log_in.this.runOnUiThread(new Runnable() {
@Override
public void run() {
try {
URL url = new URL(message);
HttpURLConnection.setFollowRedirects(false);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("HEAD");
con.connect();
Log.d("URL Result", "con.getResponseCode() IS : " + con.getResponseCode());
if ((con.getResponseCode() >= 200) && (con.getResponseCode() <= 399)) {
Log.d("URL Result", "Sucess");
Toast.makeText(getBaseContext(), "GOOD!", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(Log_in.this, MainActivity.class);
startActivity(intent);
} else
Log.d("URL Result", "con.getResponseCode() IS : " + con.getResponseCode());
} catch (Exception e)
{
e.printStackTrace();
Log.d("URL Result", "fail");
}
}
});
}
}.start();
}
});
}
我想我應該用AsyncTask
,但我不知道如何使用它在我目前的代碼中,有人有任何想法我應該怎麼做,或者我的代碼搞砸了,我應該改變它?
可能重複(http://stackoverflow.com/questions/6343166/android -os-networkonmainthreadexception) – marcinj
嗯,我不認爲這是爲什麼我問這個問題,因爲我說我不知道如何使用'Asynctask'到我的代碼 –
在谷歌搜索類型AsynTask你會得到很多教程...反正你的情況使httpUrlconnection調用doInBackground方法,並將響應代碼傳遞給onPostExecute方法的asynctask ...內部onPostExecute基於響應代碼顯示Toast或啓動一個活動 –