我正在开发一个Android应用程序,其中用户将数据发送到PHP服务器。为此,我正在使用其他Web服务,我发送大量数据,需要将近2分钟执行,我希望当用户将数据发送到PHP服务器时,服务器应该向用户发送成功消息,服务器在单独的线程中执行数据执行。怎么可能?
答案 0 :(得分:2)
您可以使用AsyncTask执行繁重的操作,而不会阻止UI线程。
我相信这段代码应该足以让你入门。
private class MyHeavyTask extends AsyncTask<Void, Void, Boolean>{
// Perform initialization here.
@Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
progressDialog = new ProgressDialog(MyActivity.this);
progressDialog.setMessage("Loading...");
progressDialog.setCancelable(false);
progressDialog.show();
}
// If an error is occured executing doInBackground()
@Override
protected void onCancelled() {
if (progressDialog.isShowing())
progressDialog.dismiss();
// Show an alert box.
AlertDialog.Builder builder = new AlertDialog.Builder(MyActivity.this);
builder.setCancelable(false)
.setTitle("Error!")
.setMessage("Error in executing your command.")
.setInverseBackgroundForced(true)
.setPositiveButton("Dismiss", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
AlertDialog alert = builder.create();
alert.show();
}
@Override
protected Boolean doInBackground(Void... arg0) {
if(!isCancelled()) {
// Perform heavy lifting here.
}
return true;
}
// After the request's performed. Here, hide the dialog boxes, inflate lists, etc.
@Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (progressDialog.isShowing())
progressDialog.dismiss();
}
}
您可以通过以下代码行调用AsyncTask:
new MyHeavyTask().execute();
希望它有助于解决您的问题。