Android 如何在doInBackground方法中调用UI或UI线程
我正在使用Android 如何在doInBackground方法中调用UI或UI线程,android,multithreading,android-asynctask,ui-thread,Android,Multithreading,Android Asynctask,Ui Thread,我正在使用AsyncTask类连接数据库。基于数据,我将创建动态EditText,复选框,而不涉及XML文件 lView=新的线性布局(本)-这里我面临着错误 有没有办法在doInBackground方法中调用UI线程 提前谢谢 @Override protected String doInBackground(String... param) { HashMap<String, bean> map = new HashMap<String, bean>();
AsyncTask
类连接数据库。基于数据,我将创建动态EditText
,复选框
,而不涉及XML文件
lView=新的线性布局(本)代码>-这里我面临着错误强>
有没有办法在doInBackground
方法中调用UI线程强>
提前谢谢
@Override
protected String doInBackground(String... param) {
HashMap<String, bean> map = new HashMap<String, bean>();
try {
url = new URL("http://localhost/app/alldata.php");
} catch (MalformedURLException e) {
Toast.makeText(getApplicationContext(), "URL Exception", Toast.LENGTH_LONG).show();
e.printStackTrace();
return null;
}
try {
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(READ_TIMEOUT);
conn.setConnectTimeout(CONNECTION_TIMEOUT);
conn.setRequestMethod("POST");
// setDoInput and setDoOutput method depict handling of both send and receive
conn.setDoInput(true);
conn.setDoOutput(true);
// Append parameters to URL
Uri.Builder builder = new Uri.Builder()
.appendQueryParameter("user_id", "user_id")
.appendQueryParameter("dpt_id","dptid");
String query = builder.build().getEncodedQuery();
// Open connection for sending data
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write(query);
writer.flush();
writer.close();
os.close();
conn.connect();
} catch (IOException e1) {
e1.printStackTrace();
}
try {
int response_code = conn.getResponseCode();
lView = new LinearLayout(this);
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
conn.disconnect();
}
return null;
}
@覆盖
受保护的字符串doInBackground(字符串…参数){
HashMap=newHashMap();
试一试{
url=新url(“http://localhost/app/alldata.php");
}捕获(格式错误){
Toast.makeText(getApplicationContext(),“URL异常”,Toast.LENGTH_LONG.show();
e、 printStackTrace();
返回null;
}
试一试{
conn=(HttpURLConnection)url.openConnection();
conn.setReadTimeout(读取超时);
连接设置连接超时(连接超时);
conn.setRequestMethod(“POST”);
//setDoInput和setDoOutput方法描述了发送和接收的处理
conn.setDoInput(真);
连接设置输出(真);
//将参数附加到URL
Uri.Builder=新的Uri.Builder()
.appendQueryParameter(“用户id”、“用户id”)
.appendQueryParameter(“dpt_id”、“dptid”);
字符串查询=builder.build().getEncodedQuery();
//打开用于发送数据的连接
OutputStream os=conn.getOutputStream();
BufferedWriter writer=新的BufferedWriter(新的OutputStreamWriter(os,“UTF-8”));
writer.write(查询);
writer.flush();
writer.close();
os.close();
连接();
}捕获(IOE1异常){
e1.printStackTrace();
}
试一试{
int response_code=conn.getResponseCode();
lView=新的线性布局(本);
}捕获(IOE异常){
e、 printStackTrace();
}捕获(JSONException e){
e、 printStackTrace();
}最后{
连接断开();
}
返回null;
}
您可以从doInBackground
方法调用publishProgress()
,并重写将在UI线程上调用的onProgressUpdate
显然,这是为了像使用一样的进步。您应该清楚地将一个工作单元划分为后台,然后在onPostExecute
中正常处理它。您可以从doInBackground
方法调用publishProgress()
,并覆盖将在UI线程上调用的onProgressUpdate
显然,这是为了像使用一样的进步。您应该清楚地将一个工作单元划分为后台,然后在onPostExecute
中正常处理它,如果您确实想与主UI线程通信,可以使用:
runOnUiThread(new Runnable() {
@Override
public void run() {
//place your code here
}
});
如果您确实想与主UI线程通信,可以使用:
runOnUiThread(new Runnable() {
@Override
public void run() {
//place your code here
}
});
更优雅的方法是传递回调函数,这样当AsyncTask
完成其工作时,它可以调用活动中的方法调用,然后您可以在那里进行必要的更改
我想建议保持这样的界面
public interface HttpResponseListener {
void httpResponseReceiver(String result);
}
HttpRequestAsyncTask mHttpRequestAsyncTask = new HttpRequestAsyncTask();
mHttpRequestAsyncTask.mHttpResponseListener = YourActivity.this;
// Start your AsyncTask
mHttpRequestAsyncTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
现在,在活动
中,您需要实现此侦听器,并且在执行异步任务
时,还需要将侦听器传递给该异步任务
public YourActivity extends Activity implements HttpResponseListener {
// ... Other functions
@Override
public void httpResponseReceiver(String result) {
int response_code = (int) Integer.parseInt(result);
// Take necessary actions here
lView = new LinearLayout(this);
}
}
现在在AsyncTask
中,首先需要有一个变量作为活动的侦听器
public class HttpRequestAsyncTask extends AsyncTask<Void, Void, String> {
// Declare the listener here
public HttpResponseListener mHttpResponseListener;
@Override
protected String doInBackground(String... param) {
HashMap<String, bean> map = new HashMap<String, bean>();
try {
url = new URL("http://localhost/app/alldata.php");
} catch (MalformedURLException e) {
Toast.makeText(getApplicationContext(), "URL Exception", Toast.LENGTH_LONG).show();
e.printStackTrace();
return null;
}
try {
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(READ_TIMEOUT);
conn.setConnectTimeout(CONNECTION_TIMEOUT);
conn.setRequestMethod("POST");
// setDoInput and setDoOutput method depict handling of both send and receive
conn.setDoInput(true);
conn.setDoOutput(true);
// Append parameters to URL
Uri.Builder builder = new Uri.Builder()
.appendQueryParameter("user_id", "user_id")
.appendQueryParameter("dpt_id","dptid");
String query = builder.build().getEncodedQuery();
// Open connection for sending data
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write(query);
writer.flush();
writer.close();
os.close();
conn.connect();
} catch (IOException e1) {
e1.printStackTrace();
}
try {
// int response_code = conn.getResponseCode(); // Return the result to onPostExecute
// lView = new LinearLayout(this); // Remove this from here
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
conn.disconnect();
}
return conn.getResponseCode() + "";
}
// Set the result here
@Override
protected void onPostExecute(final String result) {
mHttpResponseListener.httpResponseReceiver(result);
}
}
希望有帮助 更优雅的方法是传递回调函数,这样当AsyncTask
完成其工作时,它可以调用活动中的方法调用,然后您可以在那里进行必要的更改
我想建议保持这样的界面
public interface HttpResponseListener {
void httpResponseReceiver(String result);
}
HttpRequestAsyncTask mHttpRequestAsyncTask = new HttpRequestAsyncTask();
mHttpRequestAsyncTask.mHttpResponseListener = YourActivity.this;
// Start your AsyncTask
mHttpRequestAsyncTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
现在,在活动
中,您需要实现此侦听器,并且在执行异步任务
时,还需要将侦听器传递给该异步任务
public YourActivity extends Activity implements HttpResponseListener {
// ... Other functions
@Override
public void httpResponseReceiver(String result) {
int response_code = (int) Integer.parseInt(result);
// Take necessary actions here
lView = new LinearLayout(this);
}
}
现在在AsyncTask
中,首先需要有一个变量作为活动的侦听器
public class HttpRequestAsyncTask extends AsyncTask<Void, Void, String> {
// Declare the listener here
public HttpResponseListener mHttpResponseListener;
@Override
protected String doInBackground(String... param) {
HashMap<String, bean> map = new HashMap<String, bean>();
try {
url = new URL("http://localhost/app/alldata.php");
} catch (MalformedURLException e) {
Toast.makeText(getApplicationContext(), "URL Exception", Toast.LENGTH_LONG).show();
e.printStackTrace();
return null;
}
try {
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(READ_TIMEOUT);
conn.setConnectTimeout(CONNECTION_TIMEOUT);
conn.setRequestMethod("POST");
// setDoInput and setDoOutput method depict handling of both send and receive
conn.setDoInput(true);
conn.setDoOutput(true);
// Append parameters to URL
Uri.Builder builder = new Uri.Builder()
.appendQueryParameter("user_id", "user_id")
.appendQueryParameter("dpt_id","dptid");
String query = builder.build().getEncodedQuery();
// Open connection for sending data
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write(query);
writer.flush();
writer.close();
os.close();
conn.connect();
} catch (IOException e1) {
e1.printStackTrace();
}
try {
// int response_code = conn.getResponseCode(); // Return the result to onPostExecute
// lView = new LinearLayout(this); // Remove this from here
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
conn.disconnect();
}
return conn.getResponseCode() + "";
}
// Set the result here
@Override
protected void onPostExecute(final String result) {
mHttpResponseListener.httpResponseReceiver(result);
}
}
希望有帮助 您真的需要在后台创建新的LinearLayout吗?您可以在onPostExecute
中创建它您真的需要在后台创建新的LinearLayout吗?您可以在onPostExecute