我正在创建应用程序,必须通过GPS获取用户的位置,而应用程序在后台,我正在使用LocationManager,但我开始想知道哪种方法会更安全。
1)开始监听服务中的任何位置变化,并在onDestroy()中删除更新 - 但是从我读到的内容中,如果服务被终止,则无法触发onDestroy()。
2)在onDestroy()(或者onTrimMemory())中创建某种类型的GPSManager类和Application类removeUpdates。 GPSManager看起来像这样:公共类GPSManager {
Context mContext; LocationManager mLocationManager; public GPSManager(Context context){ } public void startGPSService(){ } public void stopGPSService(){ } LocationListener listener = new LocationListener() { @Override public void onLocationChanged(Location location) { } @Override public void onStatusChanged(String s, int i, Bundle bundle) { } @Override public void onProviderEnabled(String s) { } @Override public void onProviderDisabled(String s) { } };}
3)任何其他方法,我提到的更好,我不知道。
提前致谢
I'm creating app which must gets location of user through GPS while app is in background and I'm doing it using LocationManager but i started wonder which method will be safer.
1) Start listenening for any location changes in services, and removeUpdates in onDestroy() - but from what I read, if service'll be killed then onDestroy() can not be triggered.
2) Create some kind of GPSManager class and in Application class removeUpdates at onDestroy() (or maybe at onTrimMemory() ). GPSManager would be looks something like that: public class GPSManager {
Context mContext; LocationManager mLocationManager; public GPSManager(Context context){ } public void startGPSService(){ } public void stopGPSService(){ } LocationListener listener = new LocationListener() { @Override public void onLocationChanged(Location location) { } @Override public void onStatusChanged(String s, int i, Bundle bundle) { } @Override public void onProviderEnabled(String s) { } @Override public void onProviderDisabled(String s) { } };}
3) Any other method, better that I mentioned, which i doesn't know.
Thanks in advance
最满意答案
如果您的服务被终止,则会调用onDestroy或整个进程将被终止 - 在这种情况下您无需担心,操作系统会将您从要通知的应用列表中删除。 所以你对#1很好。
第二个是个坏主意。 这是没有理由删除onTrimMemory中的GPS更新,它不使用大量的RAM。 并且您希望绑定打开和关闭正在使用它的Context的更新,而不是绑定到应用程序 - 否则您将使它们保持比需要更长的时间。
If your service is killed, either onDestroy will be called or the entire process is going to be killed- in which case you don't need to worry about it, the OS will remove you from the list of apps to notify. So you're good with #1.
The second is a bad idea. THere's no reason to remove GPS updates in onTrimMemory, it doesn't use a lot of RAM. And you want to bind turning on and off updates to the Context that is using it, not to the application- otherwise you'll keep them on longer than needed.
更多推荐
发布评论