我需要创建在AsyncTask并发活动开始时创建的消失对话框。但我试图在onPostExecute()中插入dialog.dismiss(),但它根本没有显示对话框。
我正在获得GPS纬度和经度,那时我想显示ProgressDialog。并显示,但在活动结束后我无法解雇。
这是编码。
public class SearchActivity extends Activity {
private ProgressDialog dialog;
private static String PROVIDER = LocationManager.GPS_PROVIDER;
private LocationManager locationManager;
double longitude = 0.0;
double latitude = 0.0;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
Bundle extras = getIntent().getExtras();
if (extras == null) {
Toast.makeText(this, "Something Wrong existing....",
Toast.LENGTH_SHORT).show();
finish();
}
String utterance = extras.getString("utterance");
String location = extras.getString("location");
if (location == null) {
dialog = ProgressDialog.show(this, "",
"Searching your location...", true);
dialog.setCancelable(true);
new GPSLocator().execute();
}else{
Toast.makeText(getApplicationContext(), "Location is from SpeechRecognizer Activity", Toast.LENGTH_LONG).show();
}
}
public class GPSLocator extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
String info = getLocation();
return info;
}
@Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG).show();
dialog.dismiss();
}
@Override
protected void onProgressUpdate(Void... values) {
// TODO Auto-generated method stub
super.onProgressUpdate(values);
}
public String getLocation() {
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Location loc = locationManager.getLastKnownLocation(PROVIDER);
if (loc == null) {
return "GPS is not available. Location is null";
} else {
latitude = loc.getLatitude();
longitude = loc.getLongitude();
return String.valueOf(latitude) + " - "
+ String.valueOf(longitude);
}
}
}
}
答案 0 :(得分:2)
您应该在AsyncTask类中的onPreExecute()内初始化对话框 使用:
if (location == null) {
dialog = ProgressDialog.show(this, "",
"Searching your location...", true);
dialog.setCancelable(true);}
OnPreExecute顾名思义在所有其他方法之前运行,所以
1)onPreExecute:对话框初始化
2)doinbackground:做你的东西和
3)onPostExecute使用结果并关闭对话框。
价:HTTP://developer.android.com/reference/android/os/AsyncTask.html