Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/208.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 我想在应用程序到后台时启动服务,在应用程序到前台时停止服务_Android - Fatal编程技术网

Android 我想在应用程序到后台时启动服务,在应用程序到前台时停止服务

Android 我想在应用程序到后台时启动服务,在应用程序到前台时停止服务,android,Android,我已经创建了一个应用程序,我想在应用程序进入后台时启动服务,在应用程序进入前台时停止服务。 我使用了onPause()和onResume(),但我必须在每个活动中处理它。因此,当我从一个活动移动到另一个活动时,它被调用。使用布尔标志 boolean movingInApp = false; .... movingInApp = true; Intent intent... ..... public void onPause() { if(!movingInApp) { /

我已经创建了一个应用程序,我想在应用程序进入后台时启动服务,在应用程序进入前台时停止服务。 我使用了onPause()和onResume(),但我必须在每个活动中处理它。因此,当我从一个活动移动到另一个活动时,它被调用。

使用布尔标志

boolean movingInApp = false;
....
movingInApp = true;
Intent intent...
.....
public void onPause() {
    if(!movingInApp) {
        //start service
    }
}

public void onResume() {
    movingInApp = false;
    //Stop service
}
在启动任何意图等之前,通过将
movingApp
的值设置为true,您可以阻止应用启动服务。记住稍后在
onResume()方法中将其再次设置为false。如果系统使你的应用程序进入后台,这将是错误的,你的服务将启动

我使用了onPause()和onResume(),但我必须在每个活动中处理它

创建“基本”
活动

public class MyBaseActivity extends Activity {

    // Put any methods you need here that are common to all of your Activities

}
然后只需为您创建的所有
活动
类扩展基本
活动

public class ActivityOne extends MyBaseActivity {

    ...

}
通过这种方式,您的所有
活动将自动处理您需要做的事情