質問

Is there any way to handle when my android application goes into background and back?

I want to use notification service for a on-line game - I use a service, which shows an alert when something happens in the game. I want alerts to show only if my application is active (on the foreground), so I need to start my service when application goes foreground and stop it when application goes background.

Note that I cannot use Activity.OnPause/OnResume methods. I have many activities in my application, and if I'll handle OnPause/OnResume, it is possible in a moment, when a user swtches one activity to another, application will look like background, thorough it will be foreground actually

役に立ちましたか?

解決 3

Problem solved in a following way (C# code, mono for android)

class MyService : Service{
  OnSomethingHappened(){
    ActivityManager am = (ActivityManager) GetSystemService(ActivityService);
    if(am.RunningAppProcesses.Any((arg) => 
      arg.ProcessName == "myprocessname" &&
      arg.Importance == ActivityManager.RunningAppProcessInfo.ImportanceForeground
    )){
       Trace("FOREGROUND!!!!");
    }else{
       Trace("BACKGROUND!!!!");
    }
  }
}

他のヒント

Note that I cannot use Activity.OnPause/OnResume methods. I have many activities in my application, and if I'll handle OnPause/OnResume, it is possible in a moment, when a user swtches one activity to another, application will look like background, thorough it will be foreground actually

Why don't you write a base class that extends Activity and enables or disables the service in these methods? After that extend all your activities from this base activity. All you have to do is call the superclass method if you override these methods in your activties, e.g. by calling super.onResume() inside onResume(), to make sure these get still called. If you don't override them, everything works directly.

Not a clean way of doing this that I know of but,

You could perhaps send an Intent to your Service onCreate() and onPause() with a unique identifier.

You Service can then start a timer (with a delay which will be longer than the difference between onPause and onCreate being called in each activity) which, if not notified of an onCreate() within this time will set the Activity as "Paused".

If you add this functionality in a parent class which extends Activity you can then pull this same functionality into every class by extending that it rather than Activity (with the contract that you must call super.onCreate() and super.onPause() in each respective method).

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top