我正在构建一个使用 GPS 来确定用户当前国家/地区的应用程序。现在,由于 GPS 需要一段时间才能找到位置,所以在搜索时我想显示一个 ProgressDialog。
所以在我的 LocationListener 中,我调用了一个我在调用之前声明的 ProgressDialog
pd
在它显示的部分下方,我创建了一个线程来做 GPS 的东西。由于某种原因,ProgressDialog 没有显示:/
这是我的代码:
pd = ProgressDialog.show(TipCalculatorActivity.this, "", "Looking for GPS satellites...");
new Thread()
{
public void run()
{
try
{
Geocoder geocoder = new Geocoder(TipCalculatorActivity.this, Locale.getDefault());
List<Address> addresses;
try {
addresses = geocoder.getFromLocation(lat, lng, 1);
countryCode = addresses.get(0).getAddressLine(2);
}catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(TipCalculatorActivity.this, "Location is not available, please try again later.", Toast.LENGTH_LONG).show();
finish();
}
if(countryCode==null){
Toast.makeText(TipCalculatorActivity.this, "Location is not available, please try again later.", Toast.LENGTH_LONG).show();
finish();
}
Toast.makeText(TipCalculatorActivity.this, countryCode, Toast.LENGTH_LONG).show();
}
catch (Exception e)
{
Log.e("tag",e.getMessage());
}
// dismiss the progressdialog
pd.dismiss();
}
}.start();
这里有什么问题?!
谢谢!
编辑
我的新代码:我调用 AsyncTask 的地方:
LocationListener onLocationChange=new LocationListener() {
public void onLocationChanged(Location loc) {
//sets and displays the lat/long when a location is provided
lat = loc.getLatitude();
lng = loc.getLongitude();
MyAsyncTask task = new MyAsyncTask(TipCalculatorActivity.this, lng, lat);
task.execute();
Toast.makeText(TipCalculatorActivity.this, "Done :D", Toast.LENGTH_LONG).show();
}
异步任务:
public class MyAsyncTask extends AsyncTask<Void, Void, Result>{
private Activity activity;
private ProgressDialog progressDialog;
private double longitude;
private double latitude;
private String countryCode;
public MyAsyncTask(Activity activity, double longitude, double latitude) {
super();
this.activity = activity;
this.longitude = longitude;
this.latitude = latitude;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
ProgressDialog.show(activity, "", "Looking for GPS satellites...");
}
@Override
protected Result doInBackground(Void... v) {
Geocoder geocoder = new Geocoder(activity, Locale.getDefault());
List<Address> addresses;
try {
addresses = geocoder.getFromLocation(latitude, longitude, 1);
countryCode = addresses.get(0).getAddressLine(2);
}catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(activity, "Location is not available, please try again later.", Toast.LENGTH_LONG).show();
}
if(countryCode==null){
Toast.makeText(activity, "Location is not available, please try again later.", Toast.LENGTH_LONG).show();
}
Toast.makeText(activity, countryCode, Toast.LENGTH_LONG).show();
return null;
}
@Override
protected void onPostExecute(Result result) {
progressDialog.dismiss();
Toast.makeText(activity.getApplicationContext(), "Finished.",
Toast.LENGTH_LONG).show();
}
}