在我的应用程序中,我有一个广播接收器,当接收到短信中的关键字时,它会启动一项跟踪手机 GPS 位置的服务。我这样做使用 -
context.startService(new Intent(context,TrackGPS.class));
我还需要能够在收到短信中的另一个关键字时停止服务,我已尝试这样做,但 GPS 传感器仍然跟踪位置,并且 GPS 图标在屏幕顶部闪烁。我尝试使用 -
context.stopService(new Intent(context, TrackGPS.class));
我认为这可能是因为 GPS 侦听器需要取消注册。谁能帮助我在收到短信后停止该服务+停止 GPS 跟踪?提前致谢。
Solution
@Override
public int onStartCommand(Intent GPSService, int flags, int startId) {
boolean startListening = GPSService.getExtras().getBoolean("IsStartTracking");
if (startListening == true){
lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
}
else {
lm.removeUpdates(this);
stopSelf();
}
return 1;
}
我不认为你的问题是停止服务。通过终止您的服务,您并没有终止仍在寻找更新的 LocationListener 对象。
我会做以下事情。
无需停止和启动服务,只需在每次需要做某事时启动服务(开始侦听或停止侦听)即可。
在您用来告诉您想要做什么的 Intent 中添加一个额外的内容,例如:
Intent GPSService = new Intent(context, TrackGPS.class);
GPSService.putExtra("IsStartTracking", true);
context.startService(GPSService);
在服务的 onStart 方法重写中,您现在可以根据“IsStartTracking”的值在 LocationManager 的单个实例上注册和取消注册位置侦听器
boolean startListening = intent.getExtras().getBoolean("IsStartTracking");
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)