简体   繁体   中英

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.

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:

<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.

For more information refer to this link .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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