-2

I want to start a service which will run in the background, and will show latitude and longitude every 30 to 45 seconds. Below is my code which I'm using:

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);
    }
}

I'm calling my service like this:

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

This is my manifest code for service:

<service android:name="LocalService" >

Whenever I am running this code it gives me an error message that unfortunately, TimerService has stopped.

4

2 回答 2

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 的博客文章 A Deep Dive Into Location 中的概念和改编自 android-protips-location 的一些代码。

于 2012-12-26T17:21:42.573 回答
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);
    }
于 2012-12-26T17:41:56.227 回答