简单的检查了Android应用程序一个后台 [英] Simple check for Android application backgrounding

查看:96
本文介绍了简单的检查了Android应用程序一个后台的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我跟踪很多activites如何目前在我的应用程序可见(这应该是0或1)通过调用plusActivity()的每个活动的onResume()和minusActivity()从的onPause()

I'm tracking how many activites are currently visible in my app (which should be 0 or 1) by calling plusActivity() from each Activity's onResume() and minusActivity() from onPause()

加/ minusActivity在我所有MyApplication类,它扩展了应用。

plus/minusActivity are in my myApplication class, which extends Application.

方法递增和递减计数器。每次minusActivity()被调用时,它也发表了新的可运行其2秒后运行。当可运行的执行时,如果另一活动还没有开通后,最后一个关闭2秒前(如foregroundedActivities == 0,因为没有在2秒内称为plusActivity()),然后调用一个方法,做一些东西,需要发生中背景的时候。

The methods increment and decrement a counter. Every time minusActivity() is called, it also posts a runnable which runs after 2 seconds. When the runnable executes, if another activity hasn't opened after the last one closed 2 seconds ago ( e.g. foregroundedActivities == 0 because nothing called plusActivity() within 2 seconds), then it calls a method to do some stuff that needs to happen when backgrounded.

下面是一个片断:

public void plusActivity(){
    foregroundedActivities++;
}

public void minusActivity(){
    foregroundedActivities--;
    timingHandler.removeCallbacks(checkBackgroundTask);
    timingHandler.postDelayed(checkBackgroundTask, 2000);
}

public void checkIfBackgrounded(){
    if(foregroundedActivities==0){
        doWhateverWeDoWhenBackgrounded();
    }
}

public Runnable checkBackgroundTask=new Runnable(){

    @Override
    public void run() {
        checkIfBackgrounded();
    }

};

鉴于此过程中操作,并没有回调到活动参与,是实现背景检测一个可以接受的方式,还是我真的需要做的这一切都与一个服务2秒的时间内?这似乎是一个很大的开销,我看不到任何好处,因为这似乎很好地工作。

Given the 2-second timeframe this process operates in, and that no callbacks to an Activity are involved, is it an acceptable way to accomplish background detection, or do I really need to do all this with a Service? It seems like a lot of overhead and I can't see any benefits, since this seems to work fine.

推荐答案

您的解决方案可能会奏效,但我不知道。

Your solution might work but I don't know.

您可能能够使用的BroadcastReceiver 。如果您使用的BroadcastReceiver,你可以当一个活动随着你的加/减code执行的onPause()发出意向。该BroadcastReceiver的就可以可以再次执行你的应用程序......

You might be able to use a BroadcastReceiver. If you use BroadcastReceiver you can issue an Intent when an activity executes onPause() along with your plus/minus code. The BroadcastReceiver will be able to can execute your app again...

这篇关于简单的检查了Android应用程序一个后台的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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