【问题标题】:Where should I start an activity which is suppose to be triggered when app goes to background?我应该在哪里开始一个应该在应用程序进入后台时触发的活动?
【发布时间】:2020-01-21 17:21:13
【问题描述】:

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

这是我的代码:

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

【问题讨论】:

  • 根据您的代码,您正在尝试从 oncreate 启动服务。您能否用您的代码 sn-p 详细解释您的查询。
  • @Rizwan 我正在尝试在 React-Native 中实现 Headless JS,这也需要对 Adnroid 本机代码进行一些更改

标签: java android start-activity


【解决方案1】:

您可以使用 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 的代码:

class 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

【讨论】:

  • 我在 React-Native 中做,但也需要编写一些原生代码。
  • 我没有使用原生反应原生的经验
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-02
  • 2010-09-05
相关资源
最近更新 更多