我的功能可以在完成所需的时间内有所不同。我希望在此功能运行时显示进度对话框。
我知道您可以使用'Thread'来实现这一目标。有人能指出我这样做的正确方向吗?
编辑: 这是我正在使用的代码:
private class LongOperation extends AsyncTask<String, Void, String>
{
ProgressDialog dialog;
public Context context;
@Override
protected String doInBackground(String... params) {
if (!dialog.isShowing())
dialog.show(); // Just in case
return null;
}
/* (non-Javadoc)
* @see android.os.AsyncTask#onPostExecute(java.lang.Object)
*/
@Override
protected void onPostExecute(String result) {
dialog.dismiss();
}
/* (non-Javadoc)
* @see android.os.AsyncTask#onPreExecute()
*/
@Override
protected void onPreExecute()
{
dialog = ProgressDialog.show(context, "Working", "Getting amenity information", true);
}
/* (non-Javadoc)
* @see android.os.AsyncTask#onProgressUpdate(Progress[])
*/
@Override
protected void onProgressUpdate(Void... values) {
// Things to be done while execution of long running operation is in progress. For example updating ProgessDialog
}
}
这是Asnyc课程。用户从菜单中选择一个选项,然后执行:
longOperation.execute(""); // Start Async Task
GetAmenities(Trails.UserLocation); // Long function operation
答案 0 :(得分:6)
您应该使用AsyncTask
来实现此目的。请参阅Android developers website和How to use AsyncTask。
一些示例代码:
private class LongRunningTask extends AsyncTask<Void, Boolean, Boolean> {
private ProgressDialog progress;
protected void onPreExecute() {
progress = ProgressDialog.show(yourContext, "Title", "Text");
}
@Override
protected Boolean doInBackground(Void... params) {
return true;
}
protected void onPostExecute(Boolean result) {
if(result) {
progress.dismiss();
}
}
}
答案 1 :(得分:1)
答案 2 :(得分:-1)
public void onClick(View v) {
new Thread(new Runnable() {
public void run() {
Bitmap b = loadImageFromNetwork();
}
}).start();
}
取自这里 http://developer.android.com/resources/articles/painless-threading.html