我无法停止服务和BroadcastReceiver。我已经尝试了下面的代码

时间:2017-09-28 05:04:25

标签: android service broadcastreceiver

实际上我想更新我的位置每分钟到服务器,我已经查看了很多链接,但没有一个对我来说工作正常。最后我得到了这个链接

我试过这个链接:         https://deepshikhapuri.wordpress.com/2016/11/25/service-in-android/
        获取服务中的位置。我使用链接的源代码,但我无法停止服务和BroadcastReceiver

我正在启动Service和BroadcastReceiver,如下面的代码

    //Starting Service
    Intent intent = new Intent(getApplicationContext(), GoogleService.class);
                    startService(intent);

    //Starting BroadcastReceiver
    registerReceiver(broadcastReceiver, new IntentFilter(GoogleService.str_receiver));

我已尝试使用以下代码停止服务和BroadcastReceiver。

//Unregistering BroadcastReceiver
 LocalBroadcastManager.getInstance(ServiceLocActivity.this).unregisterReceiver(broadcastReceiver);

//stopping service
 Intent it = new Intent(getApplicationContext(), GoogleService.class);
 stopService(it);

以上代码无效。  我无法停止服务和广播接收器  能帮到我了吗。谢谢你。

1 个答案:

答案 0 :(得分:2)

由于意图服务在完成其循环后自动停止。将最新的lat和lon放在全局变量中。

public class LocationService extends IntentService{
public Config sharedData;
public boolean logincase = true;
ExceptionSave ex;
Intent broadcastIntent;
public String journeyState="jr_init";
public static boolean performTasks = true;
private static final String TAG = "com.live.locationservices.LocationServic";

public LocationService() {
    super(TAG);
}

@Override
protected void onHandleIntent(Intent intent) {
    if (this.performTasks) {
//If this variable is true just call your endpoint and send global variable lat and lon to server.

}
}
public class ResponseReceiver extends WakefulBroadcastReceiver {
    public static final String ACTION_RESP = "com.live.ResponseReceiver.intent.action.MESSAGE_PROCESSED";

    @Override
    public void onReceive(Context context, Intent intent) {
if(LocationServiceDriver.performTasks){
//Start your service again 1 mint post dealy
}
}

在活动销毁时取消注册您的广播接收器。完成任务后,只需设置LocationServiceDriver.performTasks = false