Pergunta

I have to show an alert box on navigating back from other apps (For ex : NotificationBar, Call, SMS etc) to my app. I need to execute some code every time when the user goes to any other app (like Call, SMS) from my app and comes back. Is there any callback for that? How can I do this?

Foi útil?

Solução

I don't know if Android supports that, but you can use an easy hack, create a boolean variable and set its value when your onPause is called. When the user goes back to another app, this value will be set. Then you can check this value in your onResume command.

But there is a problem with this approach, if you start another activity from the current activity, then that variable will be set. So whenever you are going to launch an activity from your current activity, you need to prevent that boolean variable from being set (perhaps by using another variable).

In code:

boolean backFromAnotherApp = false;
boolean activityFromMyApp = false;

public void onPause() {
    ......
    if (!activityFromMyApp)
        backFromAnotherApp = true;
    else
        activityFromMyApp = false;
}

public void onResume() {
    .....
    if (backFromAnotherApp) {
        showDialog();
        backFromAnotherApp = false;
    }
}

And anywhere in your code where you want to launch a new activity:

Intent intent = new Intent(this, AnotherActivityOfMyApp.class);
activityFromMyApp = true;
startActivity(intent);
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top