How can i determine when my application is running?
I have an application that uses a Service to fetch data in the background both while the application is running and when it's not. When it is not running i would like to 开发者_如何学Cshow a notification when there is new data, but not when the app is running.
How do i determine in my service whether the app is running or not?
I think you want to check whether a certain activity is shown. If that is true, I would use the Activity.onCreate() method to set a flag in the application instance, i.e. extend the class Application with a field "uiRunning" and check this field in your service. onDestroy() should be used to unflag the attribute. Don't forget to use your Application class also in the Manifest.xml
I would agree with the use of onCreate()/onDestroy() for a single Activity application, though an Application with multiple activities would be better off using Application.onCreate()/onTerminate() in order to avoid triggering the uiRunning state when switching activities.
This is dead easy. You use a named Mutex.
Put this in the application you want to check:
bool createdNew;
Mutex mutex = new Mutex(true, @"Global\YourAppNameHere", out createdNew);
if (createdNew)
{
var app = new YourProcess();
app.run();
mutex.Close();
}
Put this in the application that checks to make sure the other app is running:
bool createdNew;
Mutex mutex = new Mutex(true, @"Global\YourAppNameHere", out createdNew);
if (createdNew)
{
Console.WriteLine("App not running");
mutex.Close();
} else {
Console.WriteLine("App is running");
}
Another option is to implement a listener pattern and have your service manage a list of listeners with methods on your service interface for addListener() and removeListener(). Your activity can add itself as a listener after it connects to the service and remove itself onStop() (i.e. when the app is no longer visible to the user or has shutdown completely).
In your service, check the count of listeners. If there are no listeners then you know you should create your notification.
Another way to accomplish is to de-couple your data receiver to a 'service' which will always run in the background. you can have your application bind to the service and will display the data fetched by the service.
The problem with having the application in background is that Android will kill the application once it gets too old. Its always better to have such background running application as service rather then activity.
What i did do was to use a flag in my service, that the root activity sets and clears on onStart/onStop. This works pretty well.
This is how I did it and is working flawlessly with just a few lines of code:
In extended App class:
public static boolean isAppInFront = false;
In you main activity:
@Override
public void onStart() {
super.onStart();
MyApplication.isAppInFront = true;
}
@Override
public void onStop() {
super.onStop();
if (isFinishing())
MyApplication.isAppInFront = false;
}
精彩评论