我希望每次手机进入睡眠状态或关闭应用程序(即要么转到桌面或其他应用程序)时,都要将当前用户设置为未经过身份验证,以便他们始终在应用程序恢复时进行身份验证试。
我不想在每个活动的OnStop
或OnPause
方法中执行此操作,只有当应用程序当前未处于活动状态时才会这样做。
理想情况下,Application基础对象或其他全局上下文中会有OnStop
方法,类似于:
public class MyApp : Application
{
public override void OnCreate()
{
base.OnCreate();
}
}
但不幸的是,这不存在。这可能吗?
答案 0 :(得分: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;
}
}
}