如何在Android应用程序关闭时停止服务

时间:2016-04-02 06:09:54

标签: android performance

我正在开发一个应用程序,我需要每15分钟更新一次我的值。 为此我使用服务。我遇到了不同类型的服务。 与长期运行的服务一样,我们使用简单的服务,           为了与其他组件进行交互,我们使用绑定服务,           前台服务。等....

我的情况就像我需要每15分钟运行一次服务 当我的应用程序打开时,我的应用程序关闭时停止服务

我尝试过使用bind服务 http://www.truiton.com/2014/11/bound-service-example-android/ 但我无法做到这一点,我无法每15分钟运行一次服务,任何人都可以帮助我。 提前谢谢。

2 个答案:

答案 0 :(得分:1)

要在应用启动时启动该服务,请在onCreate()方法中启动它:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Intent intent = new Intent(MainActivity.this, MyService.class);
    startService(intent);

}

要停止服务,您可以使用3种不同的方法实现代码,即onPause(),onStop()和onDestroy()。

在onPause()中调用stopService()会在您的设备上发生其他事件时立即停止服务,如电话,这不是最好的停止方式,因为用户将立即返回活动电话结束。

在onDestroy()中调用stopService()也不是最佳解决方案,因为没有以用户关闭Android应用程序的所有方式调用onDestroy。

因此,停止服务的最佳方法是在onStop()方法中调用stopService(),如下所示。

@Override
protected void onStop() {
    super.onStop();
    Intent intent = new Intent(MainActivity.this, MyService.class);
    stopService(intent);
}

答案 1 :(得分:0)

如果您想在活动结束时停止服务,则必须在onDestroy()内实施代码。

以下是一个示例 -

@Override
protected void onDestroy() {
    super.onDestroy();

    Intent intent = new Intent(MainActivity.this, MyService.class);
    stopService(intent);
}

这将停止您的服务。

除非您未在活动中致电finish()或明确停止该应用,否则onDestroy()不会被调用,即使您的通话活动为onPause(在后台),您的服务仍会运行。

同样,如果您想开始服务活动,请在onCreate中实施。

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Intent intent = new Intent(MainActivity.this, MyService.class);
    startService(intent);
}

让我知道它是否有助于解决您的问题。

相关问题