异常 android.os.NetworkOnMainThreadException
Exception 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
,但我不知道如何在我当前的代码中使用它,有人知道我应该怎么做吗,或者我的代码搞砸了,我应该更改它不知何故?
new Thread() {
public void run() {
Log_in.this.runOnUiThread(new Runnable() {
您生成一个线程只是为了在 UI 线程上创建其 运行 方法 运行。这就是您获得 NetworkOnMainThreadException
的 原因。你必须使用
Log_in.this.runOnUiThread(new Runnable() {
仅对 UI 进行更改并显示您的 Toast
当我尝试 运行 这段代码时,它给出了这个错误 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
,但我不知道如何在我当前的代码中使用它,有人知道我应该怎么做吗,或者我的代码搞砸了,我应该更改它不知何故?
new Thread() {
public void run() {
Log_in.this.runOnUiThread(new Runnable() {
您生成一个线程只是为了在 UI 线程上创建其 运行 方法 运行。这就是您获得 NetworkOnMainThreadException
的 原因。你必须使用
Log_in.this.runOnUiThread(new Runnable() {
仅对 UI 进行更改并显示您的 Toast