What do you mean by "the application is running in foreground"?
If you mean there is an Activity
currently displayed on the screen, then the easiest way would be to make a base Activity
class that sets a global boolean in your `Application' class.
Custom Application
class:
public class MyApp extends Application
{
public boolean isInForeground = false;
}
Custom base Activity
class:
abstract public class ABaseActivity extends Activity
{
@Override
protected void onResume()
{
super.onResume();
((MyApp)getApplication()).isInForeground = true;
}
@Override
protected void onPause()
{
super.onPause();
((MyApp)getApplication()).isInForeground = false;
}
}
I assume you are not synchronising from your BroadcastReceiver
- you should instead be launching a Service
to do the synchronisation. Otherwise the system might kill your app - you must not be doing any long-running tasks in a BroadcastReceiver
.
So before you launch your sync service, check the application boolean to see if your app is "in foreground". Alternatively, move the check inside the sync service, which has the advantage of making the BroadcastReceiver
even simpler (I am always in favour of trying to make the receivers have as little logic as possible).
This method has the advantages that it is simple to use, understand, and requires no extra permissions.