How can I detect if my Android app is displayed? - android

I have an Android app with a service that runs in the background doing various client/server connections. How can I check in my running service if any screen from my app is displayed?

You can get the list of running processes and check if yours is in foreground with the following code:
ActivityManager actMngr = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
List<RunningAppProcessInfo> runningAppProcesses = actMngr.getRunningAppProcesses();
for (RunningAppProcessInfo pi : runningAppProcesses) {
if (getPackageName().equals(pi.processName)) {
boolean inForeground = pi.importance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
}
}
Check more at http://developer.android.com/reference/android/app/ActivityManager.RunningAppProcessInfo.html

Refreshing an Activity from service when Active
a few options:
•Have the activity register a listener object with the service in onResume() and remove it in onPause()
•Send a private broadcast, picked up by the activity via registerReceiver() when it is in the foreground
•Have the activity supply a "pending result"-style PendingIntent to the service
•Use a ResultReceiver
•Use a ContentProvider, with the activity holding onto a Cursor from the provider, and the service updating the provider
see here https://github.com/commonsguy/cw-advandroid/tree/master/AdvServices/ for a few examples.

To check whether a service is running use
ActivityManager manager = (ActivityManager) MyApp.getSharedApplication().getSystemService(Context.ACTIVITY_SERVICE);
for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (CTConstants.MyService_Name.equals(service.service.getClassName())) {
//Your service is running
}
}
if you don't want to generalize this as a common function then replace the first line with
ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);

Related

Controlling background service from another instance of an app

I made an application that fires a long-lived background service. Sometimes the application itself is closed, and the service keeps running, which is the way I want it.
The problem is that I don't know how to control that service after the caller application is closed. For example if the users re-opened the app, I'd like to give them the option whether to kill that process or keep it running.
I am able to detect if the service is running by using the following function (taken from this solution):
private boolean isMyServiceRunning(Class<?> serviceClass) {
ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
for (RunningServiceInfo service :manager.getRunningServices(Integer.MAX_VALUE)) {
if (serviceClass.getName().equals(service.service.getClassName())) {
return true;
}
}
return false;
}
I tried then calling this line from the activity, but that didn't do anything:
if(isMyServiceRunning(MyService.class)) {
stopService(new Intent(this, MyService.class));
}

Service getting called multiple times?

I am developing an application where I am running some background operations and displaying notification to the user when certain condition meets .When the user clicks on the notification it should take him to the main activity , with out restarting the service .
My problem is when I am clicking the notification it takes me to the main activity and starting my service again.I dont want to restart my service again .How can I achieve this .
I have used the following code to check weather a service running or not lease look at it
public static boolean isServiceRunning(String serviceName,Context context){
boolean serviceRunning = false;
ActivityManager am = (ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningServiceInfo> l = am.getRunningServices(50);
Iterator<ActivityManager.RunningServiceInfo> i = l.iterator();
while (i.hasNext()) {
ActivityManager.RunningServiceInfo runningServiceInfo = (ActivityManager.RunningServiceInfo) i
.next();
if(runningServiceInfo.service.getClassName().equals(serviceName)){
serviceRunning = true;
}
}
return serviceRunning;
}
I have used this piece of code and it's working fine :)
ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE))
{
if (MyService.class.getName().equals(service.service.getClassName()))
{
found = true;
}
}
you could check getIntent() on the activity and put some extra on the intent bundle of the notification that you check to start or not the service.
Note:
if a service is already running, it is not restarted.
Finally I have rectified my code.as follows
private boolean isMyServiceRunning() {
ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if ("com.example.sevicedemosolution.Myservice".equals(service.service.getClassName().toString())) {
return true;
}
}
return false;
}

Stopping service explicitly

I have an app, which contains two activities and a service and a reciever, service is used to get the location updates all the time, i will start the service in the reciever for the first time, my requirement is, i need to stop the service when my application is in foreground (running), and i need to start the service when i application is stopped. among two activities initActivity is the first activity that get launched when application starts, and the homegridActivity id the second activity, i am giving the option in homegridactivity to exit from the application. below is the code where i am starting the service and stoping the service.
class initActivity extends Activity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.app);
System.out.println("VANDROID service status inside oncreate of init" );
ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if ("com.vaayoo.android.service.VLocationFetchService".equals(service.service.getClassName())) {
Intent intent = new Intent( VUiHelper.getInstance().getApplicationContext(), VLocationFetchService.class);
boolean result = ((Vandroid)VUiHelper.getInstance().getApplicationContext()).stopService(intent);
System.out.println("VANDROID service status" + result);
manager = null;
}
}
}
}
//second Activity
Class HomeGridActivity extends Activity
{
protected void onDestroy() {
super.onDestroy();
System.out.println("Homegrid activity onDestroy called");
VUiHelper.getInstance().clearControlCache();
ActivityManager manager = (ActivityManager)getSystemService(Context.ACTIVITY_SERVICE);
for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if ("com.vaayoo.android.service.VLocationFetchService".equals(service.service.getClassName())) {
Intent intent = new Intent( VUiHelper.getInstance().getApplicationContext(), VLocationFetchService.class);
ComponentName compname =((Vandroid) VUiHelper.getInstance().getApplicationContext()).startService(intent);
System.out.println("COMPONENT NAME" + compname.toString() );
manager = null;
}
}
}
}
I am stoping the service in oncreate on the initactivity and starting the same service in ondestroy of homegridActivity, the problem i am facing is, this is working only for the first time, if i close and launch the app multiple times, service is not stoping and starting, i found that, the service is running all the time. i have made that service as start_sticky so that is should not be killed by android runtime at any point of time, i should have full control on that service to stop and start. not able to find out why it is not working all the time, why it is working only for the first time. what i am doing wrong ? how to troubleshoot this? is it because of making service as start_sticky?
This method is return true or false means.when service is ruuning than reture true otherwise false. so you can use this method when r you use just like this.
private boolean isMyServiceRunning() {
ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
for (RunningServiceInfo service : manager
.getRunningServices(Integer.MAX_VALUE)) {
if ("packagename".equals(service.service
.getClassName())) {
return true;
}
}
return false;
}
and check like that.
if (isMyServiceRunning()) {
stopService(new Intent(A.this, MusicService.class));
}

Android: check if my Service is running in the background

I am running a Service to get Notifications every 1 hour in my application.
The service definitely runs every 1 hr; I checked it using the Logcat.
But since I am starting this Service in the onResume() of my MainActivity, I want to check whether the Service is already running, and start it only if it's not running.
I used this code:
private boolean isMyServiceRunning() {
ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if ("com.android.MyApp.MyServices.NotificationsService".equals(service.service.getClassName())) {
return true;
}
}
return false;
}
But I always get false.
So I checked what output service.service.getClassName() gives. And my Service is not there in the list.
Is it because my application is unknown? or something else?
I know its bit late but this answer might help others who are looking for the same.
Have you started your service by using context.startService()?
Make sure that the manifest file contains following:
<service android:name="com.android.MyApp.MyServices.NotificationsService" />
private boolean isMyServiceRunning(Context mContext) {
ActivityManager manager = (ActivityManager) mContext
.getSystemService(Context.ACTIVITY_SERVICE);
for (RunningServiceInfo service : manager
.getRunningServices(Integer.MAX_VALUE)) {
if (**HERE_YOUR_SERVICE'S_CLASS_NAME**.class.getName().equals(
service.service.getClassName())) {
return true;
}
}
return false;
}
// i have background GPS service and i have successfully checked that my GPS service is either running or not.
// Happy coding...

Android check for running services in application

I have 3 services running in the background in my application. How do I check if they are running or not.
You can iterate through all services and check if one of them matches name of your service.
private boolean isSomeOfMyServicesRunning() {
ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if ("com.domain.myapplication".equals(service.service.getClassName()))
return true;
}
return false;
Use a static field in your service to toggle a boolean flag. Then you can check that flag by binding the service to your activities.

Categories

Resources