我应该在哪里启动应该在应用程序进入后台时触发的活动? (Android)

问题描述 投票:0回答:1

我想开始一项活动,但很奇怪,我找不到一个可以告诉我应该在哪里做的地方。

这是我的代码:

    @Override   public void onCreate() {
    super.onCreate();
    SoLoader.init(this, /* native exopackage */ false);
    initializeFlipper(this); // Remove this line if you don't want Flipper enabled

    Intent service = new Intent(getApplicationContext(), MyTaskService.class); Bundle bundle = new Bundle();
    bundle.putString("foo", "bar"); service.putExtras(bundle);
    getApplicationContext().startService(service);   
  }
java android start-activity
1个回答
0
投票

您可以使用Android Lifecycle组件检测应用程序是否将在后台运行。

请参考以下代码:

import android.app.Application
import android.arch.lifecycle.ProcessLifecycleOwner

    class SampleApp : Application() {

        private val lifecycleListener: SampleLifecycleListener by lazy {
            SampleLifecycleListener()
        }

        override fun onCreate() {
            super.onCreate()
            setupLifecycleListener()
        }

        private fun setupLifecycleListener() {
            ProcessLifecycleOwner.get().lifecycle
                    .addObserver(lifecycleListener)
        }
    }

SampleApp只是一个Android应用,在清单中声明如下:

<application
    android:name=".SampleApp"/>

lifecycleListner的代码:

类SampleLifecycleListener:LifecycleObserver {

@Inject
var component: MyLifecycleInterestedComponent

@OnLifecycleEvent(Lifecycle.Event.ON_START)
fun onMoveToForeground() {
    component.appReturnedFromBackground = true
}

@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
fun onMoveToBackground() {
}

}

在onMoveToBackground()方法中,您可以编写代码。

有关更多信息,请参考this link

© www.soinside.com 2019 - 2024. All rights reserved.