简体   繁体   English

我应该从哪里开始一个应该在应用程序进入后台时触发的活动?

[英]Where should I start an activity which is suppose to be triggered when app goes to background?

I want to start an activity but strange enough I couldn't find a single place that tells where exactly should I do that.我想开始一项活动,但很奇怪我找不到一个地方可以告诉我应该在哪里做。

Here is my code:这是我的代码:

    @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);   
  }

You can use Android Lifecycle component to detect if app is going to background.您可以使用 Android Lifecycle 组件来检测应用程序是否进入后台。

Please refer the below code :请参考以下代码:

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 is just an Android Application, declared in the manifest like: SampleApp 只是一个 Android 应用程序,在清单中声明如下:

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

Code for lifecycleListner :生命周期列表器的代码:

class SampleLifecycleListener : LifecycleObserver {

    @Inject
    var component: MyLifecycleInterestedComponent

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

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

In onMoveToBackground() method you can write your code.在 onMoveToBackground() 方法中,您可以编写代码。

For more information refer to this link .有关更多信息,请参阅此链接

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM