在输入应用前台时调用特定代码

时间:2017-10-23 11:53:42

标签: android ios xamarin.ios xamarin.android mvvmcross

我正在尝试将以下代码从xamarin.iOS移植到xamarin.android:

   public HomeView() : base(nameof(HomeView), null) {
        NSNotificationCenter.DefaultCenter.AddObserver(UIApplication.WillEnterForegroundNotification, (NSNotification not) => {
            if(NavigationController.TopViewController is HomeView)
                ScrollToCurrentDay();
        });

        DispatchQueue.MainQueue.DispatchAsync(() => {
            ScrollToCurrentDay();
        });
    }

如果第一次加载视图或应用程序进入前台时,如何调用函数?我尝试使用BroadcastReceiver,请参阅here。是否有更简单,更短的方式?

1 个答案:

答案 0 :(得分:0)

  

在输入应用前景时调用特定代码

正如@MilanG所说,当您的应用从后台出现前景时,系统会调用Activity OnResume()方法:

protected override void OnResume()
{
    base.OnResume();
    ScrollToCurrentDay();
}

正如文件所说:

  

当活动进入Started状态时,系统会调用此回调。 onStart()调用使活动对用户可见,因为应用程序准备活动以进入前台并变为交互式。

但是,当Activityopen by another Activity时,也会调用 OnResume()的{​​{1}}方法。

在后台或前台,没有任何直接的方法来获取应用程序状态,您需要在Activity的生命周期中添加一个监听器。

解决方案1:

您可以创建Activity来镜像活动生命周期回调,每隔一个BaseActivity必须扩展此Activity 。然后,您可以跟踪您的生命周期中的活动,并做出相应的反应。有关更多详细信息,请阅读此document。这是一个例子:

BaseActivity

解决方案2:

您可以注册ActivityLifecycleCallbacks来镜像所有活动生命周期回调,因为您使用public abstract class BaseActivity : AppCompatActivity { public static bool isAppWentToBg = false; public static bool isWindowFocused = false; public static bool isMenuOpened = false; public static bool isBackPressed = false; protected override void OnStart() { applicationWillEnterForeground(); base.OnStart(); } private void applicationWillEnterForeground() { if (isAppWentToBg) { isAppWentToBg = false; Toast.MakeText(ApplicationContext, "App is in foreground", ToastLength.Short).Show(); } } protected override void OnStop() { base.OnStop(); applicationdidenterbackground(); } public void applicationdidenterbackground() { if (!isWindowFocused) { isAppWentToBg = true; Toast.MakeText(ApplicationContext, "App is Going to Background", ToastLength.Short).Show(); } } //Called when the current Window of the activity gains or loses focus. public override void OnWindowFocusChanged(bool hasFocus) { isWindowFocused = hasFocus; if (isBackPressed && !hasFocus) { isBackPressed = false; isWindowFocused = true; } base.OnWindowFocusChanged(hasFocus); } public override void OnBackPressed() { base.OnBackPressed(); if (this.GetType() == typeof(MainActivity)) { } else { isBackPressed = true; } } } ,建议您使用此解决方案:

MvvmCross