确定是否有任何活动可见(app in background)

时间:2017-10-08 17:59:04

标签: android

有没有办法确定是否有任何活动可见(应用程序在后台的情况)。我试图在没有会话的情况下实现取消记录机制,我确实处理了屏幕关闭/锁定,超时,按下主页按钮的情况,但是当另一个应用程序正在启动并将我的应用程序放在后台时,那就是问题所在。

或者检查某项活动是否暂停的方法,因为有一个意图被调用来打开一项新活动。这样,我就会打开三个活动confessionusersA和当前B。所以,

C

2 个答案:

答案 0 :(得分:0)

好吧,当你的应用程序进入后台时,会调用当前onPause()的函数Activity

您可以轻松覆盖它并将逻辑放在那里

@Override 
protected void onPause() {
    // Another Activity has started, user has closed the application 
    // or started another one...
}

当您的Activity再次进入前台时,会触发onResume()

@Override
protected void onResume() {
     // the user re-opened your application, or came back from
     // another activity
}

请注意,在onResume()之后,onCreate()始终

修改

如果我理解正确,那么只要有可见的Activity就知道了。不是哪一个......

在这种情况下,@ Journey在下方的回答应该符合您的需求。

我当时想知道,从那里你将检查你的行为是否可见。我想你会使用Service或某种背景机制。

在这种情况下,常用模式是LocalBroadcastManager

我写了一个相关的答案here,虽然你可以在SO上找到很多其他的答案。

基本上,在您的每项活动中,当Receiver可见时注册Activity,并在进入后台时取消注册。

Service发送IntentActivity可见的Receiver会响应。

在您的活动中创建this.localBroadcastReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { // Do what you have to do here if you receive data from the Service / Background Task } }

Filter

设置public static final IntentFilter SIGNAL_FILTER = new IntentFilter("com.you.yourapp.MY_SIGNAL"); 以区分您的信号:

Receiver

每次Activities可见时,请务必注册@Override protected void onResume() { // Listen if a Service send me some data LocalBroadcastManager.getInstance(getApplicationContext()).registerReceiver(this.localBroadcastReceiver, SIGNAL_FILTER); }

Activity

@Override protected void onPause() { // I'm going to the background, no need to listen to anything anymore... LocalBroadcastManager.getInstance(getApplicationContext()).unregisterReceiver(this.localBroadcastReceiver); } 关闭时,停止收听信号:

Service

当您的Activity或后台任务想要将数据发送到当前可见的final Intent intent = new Intent(); intent.setAction(SomeActivity.SIGNAL_FILTER); // put your data in intent LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(intent); 时,您可以致电

ref

如果某个活动可见,它将收到意图,否则不会发生任何事情。

答案 1 :(得分:0)

如果活动在后台,请尝试在执行任何操作之前检查isDestroyed()。