按下后退时不要停止服务

时间:2015-08-12 22:42:05

标签: android

我有Map activityMainActivity。 MainActivity与包含LocationManager的Service类进行通信。在MainActivity中单击按钮后,将打开Map Activity。

我想在应用程序关闭或MainActivity菜单中的Trackingservice复选框按钮设置为false时停止服务类中的Locationmanager(这是另一个按钮而不是启动Map活动的按钮)但是我当我按下back按钮并且我想从Map转到MainActivity时不想停止它,因为当前状态为onBackPressed(),然后在地图中调用onDestroy()活动之后,正在调用onDestroy()类中的Trackingservice方法,从而停止跟踪服务。

我怎样才能达到?

正如我所说,我希望在后台关闭应用程序时停止服务(无论是在MainActivity或Map活动中)还是跟踪服务复选框按钮设置为false,此时工作正常但我不要在按下back按钮时停止服务,因为正在停止操作,此按钮暂时不起作用。

MainActivity

public class MainActivity extends ActionBarActivity implements
        AsyncTaskCallback {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.route_available);
        Intent i = new Intent(this, TrackingService.class);
        startService(i);
    }

@Override
protected void onDestroy() {
    super.onDestroy();
    Intent i = new Intent(this, TrackingService.class);
    stopService(i);
}
}

服务类:

public class TrackingService extends Service implements AsyncTaskCallback,
        LocationListener {
    LocationManager lm;

    private void detectLocation() {
        lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 15 * 1000, 0,
                this);
        enableGPS(lm);

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        unregisterReceiver(wifi_receiver);
        lm.removeUpdates(this);

    }
}

地图活动

public class Map extends FragmentActivity implements OnMapReadyCallback {

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        markerMap.clear();      
        stopAlarm();

    }

    @Override
    protected void onStop() {
        super.onStop();
        GetLLRD.shouldContinue = false;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        markerMap.clear();      
        stopAlarm();
        Intent i = new Intent(this, TrackingService.class);
        stopService(i);

    }

  }

2 个答案:

答案 0 :(得分:3)

您必须绑定服务like here in doc。关于堆栈的问题,答案甚至是工作实例(here probably the best)都有很多问题。那么您可以决定何时解除绑定并销毁服务以及何时将其保留在后台。其他活动也可以绑定到此服务并进行通信

答案 1 :(得分:1)

你可以将你的应用程序放在后台而不是完成它。

@Override
public void onBackPressed() {
 moveTaskToBack(true);
// super.onBackPressed();
}
相关问题