如何在服务中获取Android中的位置

时间:2012-12-26 17:17:07

标签: android service gps locationlistener

我想启动一个将在后台运行的服务,并且每隔30到45秒显示一次纬度和经度。 以下是我正在使用的代码:

public class LocalService extends Service implements LocationListener {
    private final static String TAG = "LocalService";
    LocationManager lm;


    public LocalService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        subscribeToLocationUpdates();
    }

    public void onLocationChanged(Location loc) {
        Log.d(TAG, loc.toString());
        Toast.makeText(getApplicationContext(), loc.getLatitude() + " - " + loc.getLongitude(), Toast.LENGTH_LONG).show();
        Log.i("Location", loc.getLatitude() + " - " + loc.getLongitude());
    }

    public void onProviderEnabled(String s) {
    }

    public void onProviderDisabled(String s) {
    }

    public void onStatusChanged(String s, int i, Bundle b) {
    }

    public void subscribeToLocationUpdates() {
        this.lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        this.lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 30, 0, this);
    }
}

我正在调用我的服务:

startService(new Intent(TimerServiceActivity.this,
         LocalService.class));

这是我的服务清单代码:

<service android:name="LocalService" >

每当我运行此代码时,它会给我一条错误消息,遗憾的是TimerService已停止。

2 个答案:

答案 0 :(得分:1)

您是否在清单中添加了权限?

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

我强烈建议使用针对电池使用而优化的库,并且使用起来非常简单:

http://code.google.com/p/little-fluffy-location-library/

  

基于以下概念,以及一些改编自的代码,   由Reto Meier撰写的android-protips-location,来自他的博客文章A Deep Dive   进入位置。

答案 1 :(得分:1)

您需要先订阅提供商。为此,请在onCreate()方法的开头添加:

            locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    // Define the criteria how to select the locatioin provider -> use
    // default
    Criteria criteria = new Criteria();
    criteria.setAccuracy(Criteria.ACCURACY_FINE);
    provider = locationManager.getBestProvider(criteria, false);

    Location location = locationManager.getLastKnownLocation(provider);
    Log.v(TAG, "Init");
    // Initialize the location fields
    if (location != null) {
        System.out.println("Provider " + provider + " has been selected.");
        onLocationChanged(location);
    }