安卓:当应用程序作为一个整体(而不是个人活动)暂停/退出检测? [英] Android: Detect when an application as a whole (not individual Activities) is paused/exited?

查看:168
本文介绍了安卓:当应用程序作为一个整体(而不是个人活动)暂停/退出检测?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用程序启动一个活动/绑定到一个服务(也是我的应用程序)。我想该服务继续运行,只要该应用作为一个整体仍处于前台,无论哪个的活性是有效的。但我需要确保,当应用程序作为一个整体被暂停(HOME键/后退键)的服务被停止。

One of the Activities in my app starts/binds to a service (also part of my app). I would like that service to continue running as long as the app as a whole is still in the foreground, regardless of which Activity is active. But I need to make sure that the service is stopped when the app as a whole is paused (home button/back button).

我如何做到这一点的应用程序级别,而不是活动水平?

How can I do that on an application level rather than an Activity level?

推荐答案

最简单的方法是有一个单身它会跟踪每个活动的状态,比如只显示一个活动为例:

The easiest way is to have a singleton which keeps a track of the state of each activity, e.g showing just one activity as an example:

public class ActivityStates {

    private static  ActivityStates  ref = null;
    private static int firstAct     = ACTIVITY_GONE;

    public static synchronized  ActivityStates getInstance() {
        if (ref == null) {
            ref = new ActivityStates();
        }
        return ref;
    }

    public int getFirstAct() {
        return firstAct;
    }

    public void setFirstAct(int arg) {
        this.firstAct = arg;
    }
}

.. 并定义一些静态常量,你可以导入

.. and define some static constants that you can import

public static final int ACTIVITY_GONE       = 0;
public static final int ACTIVITY_BACKGROUND = 1;
public static final int ACTIVITY_FOREGROUND = 2;

然后在每个活动有一个方法

then in each activity have a method

private void setActivityState(int state){
        ActivityStates as = ActivityStates.getInstance();
        as.setFirstAct(state);
}

然后在你的onResume(),在onPause,的onDestroy()当您在onResume进入这些方法,例如,有可以设置activitiy的状态

Then in your onResume(), onPause, onDestroy() you can set the activitiy's state when you enter these methods, e.g in onResume have

setActivityState(ACTIVITY_FOREGROUND)

在的onDestroy()有

in onDestroy() have

setActivityState(ACTIVITY_GONE)

然后,在你的服务,或任何你想要的,你可以使用get方法来找出每个活动的状态,并决定该怎么做。

Then in you service, or wherever you want , you can use the get methods to find out the state of each activity and decide what to do.

这篇关于安卓:当应用程序作为一个整体(而不是个人活动)暂停/退出检测?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆