2013-05-14 108 views
0

我正在研究一个必须在后台工作并将位置更新发送到服务器的应用程序。服务停止更新位置

该代码非常简单,正常工作。有一种服务具有一个Timer,它每15秒向服务器发送一次更新,并且还实现LocationListener接口。

我不认为让所有的代码将是有益的,这里是我如何设置类:

@Override 
public void onCreate() { 
    super.onCreate(); 

    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); 
    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER   , 5000, 10.0f, this); 
    locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER , 5000, 10.0f, this); 

    //Ping Task sends updates to the Server 
    Ping_Timer.scheduleAtFixedRate(new Ping_Task(), 5000, Ping_Task.TIME_GET_JOBS*1000); 
} 

在实践中我有一些问题,我的代码。服务应该在后台运行,即使Service stop在那里有一个GCM系统可以在后台重新启动服务。

即使有了这些保护措施,我仍然有问题,有时应用程序不再更新位置,即使明确表示服务仍在运行。在Google地图应用程序中,我可以看到该位置在那里是正确的,但在我的应用程序中没有。这怎么可能,为什么我不再获得'onLocationChanged'事件。

感谢您的帮助。

回答

2

首先,我不确定Service的生命周期。但我使用onStart()方法的Service下面的代码。在Context上调用startService(Intent)方法后调用此方法。我想,你可以在onCreate()方法中做到这一点。

实现位置监听器:

private final static LocationListener listener = new LocationListener() { 

    @Override 
    public void onLocationChanged(Location location) { 
     //locationHandler will be created below. 
     Message.obtain(locationHandler, 0, location.getLatitude() + ", " + location.getLongitude()).sendToTarget(); 
    } 

    @Override 
    public void onProviderDisabled(String provider) { 
    } 

    @Override 
    public void onProviderEnabled(String provider) { 
    } 

    @Override 
    public void onStatusChanged(String provider, int status, Bundle extras) { 
    } 
}; 

给你的听众的方法,而不是this

locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 10.0f, listener); 
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 5000, 10.0f, listener); 

onStart()方法Service实现这个监听器的处理程序。

Handler locationHandler = new Handler() { 
    @Override 
    public void handleMessage(android.os.Message msg) { 
     String location = (String) msg.obj; 

     //do what you wanna do with this location 

    } 
} 

这就是我的做法。

+0

这是一项服务。 – nickik 2013-05-15 13:47:28

+0

更新了我的答案。一探究竟。 – slhddn 2013-05-15 14:11:45

+0

为什么我要绕过android.os.Message?我可以直接在LocationListener中做我所做的事情。 – nickik 2013-05-21 17:25:59

相关问题