2 回答
TA贡献1829条经验 获得超13个赞
这就是谷歌所说的。
为避免创建无响应的 UI,请勿在 UI 线程上执行网络操作。默认情况下,Android 3.0(API 级别 11)及更高版本要求您在主 UI 线程以外的线程上执行网络操作;如果不这样做,NetworkOnMainThreadException则会抛出 a。
您需要在单独的线程中执行您的 HTTP 请求。这可以在一个AsyncTask.
在您的情况下,您需要在下载完成后更新 UI。使用监听器通知 UI 线程
public interface ResultsListener {
public void onResultsSucceeded(String result);
}
这是来自 Google 开发人员指南的示例。我对其进行了编辑,并在结果完成后调用了侦听器。
private class HttpRequestTask extends AsyncTask<URL, Integer, String> {
public void setOnResultsListener(ResultsListener listener) {
this.listener = listener;
}
protected String doInBackground(URL... urls) {
int count = urls.length;
for (int i = 0; i < count; i++) {
String httpResult = // Do your HTTP requests here
// Escape early if cancel() is called
if (isCancelled()) break;
}
return httpResult;
}
// use this method if you need to show the progress (eg. in a progress bar in your UI)
protected void onProgressUpdate(Integer... progress) {
setProgressPercent(progress[0]);
}
// this method is called after the download finished.
protected void onPostExecute(String result) {
showDialog("Downloaded " + result);
listener.onResultsSucceded(result);
}
}
new HttpRequestTask().execute(url)现在您可以通过调用Activity来执行任务。您的活动需要实施ResultsListener. 在该onResultsSucceeded方法中,您可以更新您的 UI 元素。
你看,你可以在你的例子中很好地使用 AsyncTask。你只需要重新格式化你的代码。
TA贡献1801条经验 获得超8个赞
我使用 AsyncTask 但不再工作请检查我的代码
public class RegisterActivity extends Activity {
EditText editusername;
EditText editpassword;
String username;
String password;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.register);
editusername = (EditText) findViewById(R.id.username_reg);
editpassword = (EditText) findViewById(R.id.password_reg);
Button reg_btn = (Button) findViewById(R.id.reg_btn);
reg_btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
username = editusername.getText().toString();
password = editpassword.getText().toString();
new RegisterAsyncTask().execute();
}
});
}
class RegisterAsyncTask extends AsyncTask<Void, Void, Boolean> {
private void postData(String username, String password) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("myurl");
try {
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3);
nameValuePairs.add(new BasicNameValuePair("username", username));
nameValuePairs.add(new BasicNameValuePair("password", password));
nameValuePairs.add(new BasicNameValuePair("action", "insert"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
}
catch (Exception e)
{
Log.e("log_tag", "Error: " + e.toString());
}
}
@Override
protected Boolean doInBackground(Void... params) {
postData(username, password);
return null;
}
}}
添加回答
举报
