是否有应用程序级别 OnStop 方法,而不仅仅是活动级别



我希望将当前用户设置为每次手机进入睡眠状态或应用程序关闭(即转到桌面或其他应用程序)时不进行身份验证,以便他们始终必须在应用程序再次打开时进行身份验证。

我不想在每个活动的OnStopOnPause方法中执行此操作,仅在应用程序当前未处于活动状态时执行此操作。

理想情况下,在应用程序基对象或其他全局上下文中将有一个OnStop方法,类似于以下内容:

public class MyApp : Application
{
    public override void OnCreate()
    {
        base.OnCreate();
    }
}

但不幸的是,这并不存在。这可能吗?

事实证明没有。解决方案是在不活动计时器中进行测试,例如:

private void InactivityTimer_Elapsed(object sender, ElapsedEventArgs e)
{
    _secondsElapsed += 1;
    if (_screenEventReceiver.IsScreenOff || IsApplicationSentToBackground(this.ApplicationContext))
    {
       // do things that you would OnStop here
    }
}
public static bool IsApplicationSentToBackground(Context context) 
{
    try
    {
        var am = (ActivityManager)Context.GetSystemService(Context.ActivityService);
        var tasks = am.GetRunningTasks(1);
        if (tasks.Count > 0)
        {
            var topActivity = tasks[0].TopActivity;
            if (topActivity.PackageName != context.PackageName)
            {
                return true;
            }
        }
    }
    catch (System.Exception ex)
    {
        Errors.Handle(Context, ex);
        throw;
    }
    return false;
}
    private class ScreenEventReceiver : BroadcastReceiver
    {
        public bool IsScreenOff { get; private set; }
        public override void OnReceive(Context context, Intent intent)
        {
            if (intent.Action == Intent.ActionScreenOff)
            {
                IsScreenOff = true;
            }
            else
            {
                IsScreenOff = true;
            }
        }
    }

相关内容

最新更新