Android monitoring application front / background switching instance code

preface

This week, we received a demand to display our advertisements when the application switches from the background to the foreground. In fact, the display page can reuse the previous open screen advertising page. The only problem is how to monitor the application from the background to the foreground.

text

Among many methods, I have adopted the following approach. Without much nonsense, let's look directly at the code:

Declare in manifest file

Override the ontrimmemory method in myapplication:

The ontrimmemory method provides a suitable time for developers to release some unused resources, so that our application can survive longer in the background. The level parameter represents the current state of our application in memory, trim_ MEMORY_ UI_ Hidden means that the application has switched from the front console to the background. At this time, we can mark the application to switch to the background.

Next, you need to monitor when the application returns to the foreground:

We use registeractivitylifecyclecallbacks to listen to the life cycle callbacks of all activities and judge in the onactivityresumed method: if the onresume method of the activity is called and has been marked as the background state, we can judge that the app has returned to the foreground.

The following is the log output:

The above is my solution to this problem.

ending

This scheme requires an API greater than or equal to 14, because the registeractivitylifecycle callbacks method requires an API greater than 14.

The above is the whole content of this article. I hope it will be helpful to your study, and I hope you can support programming tips.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>