How can I tell if my Application is resumed from background?

前端 未结 5 2041
北恋
北恋 2021-02-04 10:57

I want to lock my application when it goes in background and when it resumes I want to display my own lock screen. The lock screen is an Activity of my application.

Aft

5条回答
  •  没有蜡笔的小新
    2021-02-04 11:44

    For anyone that is interested, if I understand your question correctly, I was looking into similar functionality and wasn't happy with what I found. I wanted to determine when the activity was being resumed from the background vs. when it was being resumed from a called activity.

    I ended up utilizing a boolean flag that get's set from startActivity that will allow the calling Activity to determine whether or not it is resuming from the called Activity or from the background. Something like this

    private static boolean RESUME_FROM_ACTIVITY;
    
    @Override
    public void onResume(){
        super.onResume();
        if(!RESUME_FROM_ACTIVITY){
            // do what you want like lock the screen
        }
        RESUME_FROM_ACTIVITY = false;
    }
    
    @Override
    public void startActivity(Intent intent){
        RESUME_FROM_ACTIVITY = true;
        super.startActivity(intent);
    }
    

    Because of the way that Android handles statics and the activity stack (read more in this blog post), this should work conceptually. A bit more of an explanation, the static should be one of the last things that gets cleared from memory when your app is running if the heap space gets too large. The activity will not be destroyed without the stack itself being destroyed, so onResume will be called and it will check the static flag to see if it is coming from another activity or from the background.

    The static is likely even overkill, as again the activity itself won't be destroyed and it's globals will be held as long as possible. This is only conceptual and we are still in the middle of stress testing it, but it is an option. If we find any issues I will update this post.

提交回复
热议问题