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;
}
}}
添加回答
舉報
