我试图从asynctask中获取用户的当前位置。我的应用程序取决于纬度和经度值。我试图向用户显示ProgressDialog,直到获取该位置。
问题: - 位置值始终为null。我知道获取GPS位置需要时间。但即使有时等待,我的位置值也为空。它总是空的。
以下是我的代码: -
public class MainActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//some action …
}
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
if (id == R.id.action_settings)
{
return true;
}
if(id == R.id.action_location)
{
LocationTask locGetter = new LocationTask(MainActivity.this);
locGetter.execute();
}
return super.onOptionsItemSelected(item);
}
}
下面是我的AsyncTask
public class LocationTask extends AsyncTask<Void,Void,Void> implements LocationListener
{
private ProgressDialog dialog;
private Activity callingActivity;
LocationManager locationManager;
String provider = LocationManager.GPS_PROVIDER;
public LocationTask(Activity activity)
{
callingActivity = activity;
}
@Override
protected void onPreExecute()
{
dialog= ProgressDialog.show(callingActivity,"Getting Co-ordinates","Please Wait....");
}
@Override
protected Void doInBackground(Void... voids)
{
locationManager = (LocationManager) callingActivity.getSystemService(Context.LOCATION_SERVICE);
Location location = locationManager.getLastKnownLocation(provider);
showLocation(location);
return null;
}
private void showLocation(Location location)
{
if(location == null)
{
Log.d("Location","Failed to get location");
}
else
{
Log.d("Location","Latitude :- "+location.getLatitude()+" Longitude :- "+location.getLongitude());
}
}
@Override
protected void onPostExecute(Void aVoid)
{
dialog.dismiss();
super.onPostExecute(aVoid);
}
@Override
public void onLocationChanged(Location location)
{
showLocation(location);
}
@Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
@Override
public void onProviderEnabled(String s) {
}
@Override
public void onProviderDisabled(String s) {
}
}
更新: -
正如Ivan所说,我修改了我的AsyncTask以获得如下位置: -
@Override
protected Void doInBackground(Void... voids) {
locationManager = (LocationManager) callingActivity.getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(provider,0,0,this);
if(locationManager != null) {
Location location = locationManager.getLastKnownLocation(provider);
showLocation(location);
}
return null;
}
但是这个抛出的窗户泄露了#34; onPrexecute()方法中dialog= ProgressDialog.show(callingActivity,"Getting Co-ordinates","Please Wait....");
内的异常。
答案 0 :(得分:0)
在我看来,您可能错过了requestLocationUpdates(...)来电。
请检查此related question以便更好地了解可能遗漏的内容,因为它确实不会出现在AsyncTask内部的问题,尽管我并不是真的看到需要在您的代码段中使用AsyncTask。