2

我想将我的当前用户设置为每次手机进入睡眠状态或应用程序关闭(即进入桌面或其他应用程序)时不进行身份验证,这样当应用程序再次打开时他们总是必须进行身份验证。

我不想在每个活动的OnStoporOnPause方法中这样做,只有当应用程序当前不活动时。

理想情况下,Application 基础对象或其他一些全局上下文中会有一个OnStop方法,类似于:

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

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

4

1 回答 1

0

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

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;
            }
        }
    }
于 2013-09-25T10:36:33.917 回答