0

我正在尝试创建一个 android 服务,它将每 5 分钟更新一次用户的位置。我正在使用 DDMS 将坐标发送到运行良好的模拟器。我需要转换这些坐标并获取位置,例如:纽约并使用 Toast,将其打印在屏幕上。我没有使用任何地图,我正在尝试使用地理编码器将 DDMS 提供的坐标转换为位置。我没有收到错误,但似乎坐标没有被转换为位置,屏幕上没有显示任何内容。请帮助已经为此苦苦挣扎了很长时间。这是我的代码。谢谢

public class GetLocationService extends Service {
protected LocationManager locationManager;
Button start;

@Override
public IBinder onBind(Intent arg0) {
    // TODO Auto-generated method stub
    return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId){
    LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
    LocationListener ll = new MyLocListener();
    Location location = new Location("abc");
    ll.onLocationChanged(location ); 
    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0, ll);
    return START_STICKY;
}

private class MyLocListener implements LocationListener {
public void onLocationChanged(Location location) {
     if (location != null) {
    Log.d("LOCATION CHANGED", location.getLatitude() + "");
    Log.d("LOCATION CHANGED", location.getLongitude() + "");
    }
    double latitude = location.getLatitude();
    double longitude = location.getLongitude();
    Toast.makeText(getApplicationContext(),
    location.getLatitude() + "" + location.getLongitude(),
    Toast.LENGTH_LONG).show();
    try{
         Geocoder geo = new Geocoder(GetLocationService.this.getApplicationContext(), Locale.getDefault());
         List<Address> addresses = geo.getFromLocation(latitude, longitude, 1);
             if (addresses.size() > 0) {       
                Log.d("TAG",addresses.get(0).getFeatureName() + ", " + addresses.get(0).getLocality() +"," + addresses.get(0).getAdminArea() + "," + addresses.get(0).getCountryName());
             }
             Toast.makeText(getApplicationContext(),
                     addresses.get(0).getFeatureName() + ", " + addresses.get(0).getLocality() +"," + addresses.get(0).getAdminArea() + "," + addresses.get(0).getCountryName(),
                        Toast.LENGTH_LONG).show();
          }

        catch (Exception e) {
            e.printStackTrace(); 
        }
        }
     }
   }

////启动服务////

 public class MyService extends Activity {

 @Override
    protected void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    setContentView(R.layout.service);
    startService(new Intent(getBaseContext(), GetLocationService.class));

  }
}

在此处输入图像描述

4

1 回答 1

0

好的,你的日志语句通过了吗?此外,您的 toast 不会显示,因为您传递给它的上下文是服务上下文。该服务不是用户界面的一部分。因此不会显示服务上下文。应用程序上下文可能工作......但你真的应该使用当前活动的上下文。

于 2012-07-10T18:02:57.840 回答