Forum Xamarin.Forms
We are excited to announce that the Xamarin Forums are moving to the new Microsoft Q&A experience. Q&A is the home for technical questions and answers at across all products at Microsoft now including Xamarin!

We encourage you to head over to Microsoft Q&A for .NET for posting new questions and get involved today.

Xamarin Forms Android how to detect app coming from background

KalyanMungiKalyanMungi USMember ✭✭

I had looked for this thread on Xamarin forums but never find.

Later I implemented this myself and sharing this because someone might find it useful

On Android, we don't have any base methods to override if app is coming from background. We have OnStart()/OnStop() , OnResume/OnPause but they'll also be get called when app is intially loaded and when device is locked.

So, for instance if we want to run a block of code only when app comes from background, there is no base method.

Please find the code snippet below, hoping it would be useful

`protected override void OnStart ()
{
base.OnStart ();
if (isAppWentToBackground) {
ApplicationWillEnterForeground ();
}
}

    void ApplicationWillEnterForeground ()
    {
        //App coming from background
        System.Diagnostics.Debug.WriteLine ("App came to foreground");
        isAppWentToBackground = false;
    }

    protected override void OnStop ()
    {
        KeyguardManager km = (KeyguardManager)BaseContext?.GetSystemService (Context.KeyguardService);
        if (km != null && !km.IsKeyguardLocked) {

            ApplicationWillEnterBackground ();
        }
        base.OnStop ();
    }

    void ApplicationWillEnterBackground ()
    {
        //app went to background
        System.Diagnostics.Debug.WriteLine ("App went to Background");
        isAppWentToBackground = true;
    }

`

Best Answer

  • KalyanMungiKalyanMungi USMember ✭✭
    Accepted Answer

    @DhruvGohil. Thanks but I'm not asking a question, posting my implementation if some one can find useful

Answers

  • DhruvGohilDhruvGohil USMember ✭✭✭

    Have you tried OnResume method which is in App.cs in your shared code ?

  • KalyanMungiKalyanMungi USMember ✭✭
    Accepted Answer

    @DhruvGohil. Thanks but I'm not asking a question, posting my implementation if some one can find useful

  • RichardAmissRichardAmiss USMember ✭✭
    edited April 2017

    @ KalyanMungi - Your solution detects IsKeyguardLocked which has nothing to do with whether the app enters/exits a running background state.

    OnSleep/Resume events fire when the app goes to /returns from the background, and always triggers, whether or not the app is doing work in the background. You should set a bool variable when you enter/exit your background function/routine and use that to determine the status.

Sign In or Register to comment.