【发布时间】:2015-07-15 08:37:49
【问题描述】:
我正在尝试从异步任务中获取用户的当前位置。我的应用程序取决于纬度和经度值。我正在尝试向用户显示 ProgressDialog,直到获取位置。
问题 :- 位置值始终为空。我知道获取 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);
}
}
下面是我的异步任务
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;
}
但这会在 onPrexecute() 方法内的dialog= ProgressDialog.show(callingActivity,"Getting Co-ordinates","Please Wait...."); 中引发“windows leaked”异常。
【问题讨论】:
-
您的程序需要用户明确许可才能访问 GPS 坐标
-
我已将权限添加到 ACCESS_FINE_LOCATION、ACCESS_COARSE_LOCATION、INTERNET。
标签: android android-asynctask gps android-location