how to check the top activity from android app in background service - android

In my app i want to check whethere any other app launches or not from my app.So i am currently usimg Activitymanager to find the top activity like this
ActivityManager am = (ActivityManager) this.getSystemService(ACTIVITY_SERVICE);
List< ActivityManager.RunningTaskInfo > taskInfo = am.getRunningTasks(1);
Log.d("topActivity", "CURRENT Activity ::"
+ taskInfo.get(0).topActivity.getClassName());
ComponentName componentInfo = taskInfo.get(0).topActivity;
componentInfo.getPackageName();
But i want to run this code in background service.So that i can detect When other app launches through this.So is there any idea to do this.Plz help me.thanks

By using service you can achieve this..
public void checkActivity() {
handler = new Handler();
activityRunnable = new ActivityRunnable();
handler.postDelayed(activityRunnable, 500);
}
private class ActivityRunnable implements Runnable {
#Override
public void run() {
ActivityManager manager = (ActivityManager) getApplicationContext()
.getSystemService(Context.ACTIVITY_SERVICE);
List<RunningTaskInfo> runningTasks = manager.getRunningTasks(1);
if (runningTasks != null && runningTasks.size() > 0) {
ComponentName topActivity = runningTasks.get(0).topActivity;
// Here you can get the TopActivity for every 500ms
if(!topActivity.getPackageName().equals(getPackageName())){
// Other Application is opened
}
handler.postDelayed(this, 500);
}
}
}
Call the checkActivity() in onCreate of service and dont forgot to remove the handler.removeCallbacks(activityRunnable); callbacks in onDestroy
start the service in LauncherActivity onCreate and stop the service in LauncherActivity onDestroy
Note: Dont forgot to add the permission in your manifest
<uses-permission android:name="android.permission.GET_TASKS" />

You should use Service for this. Then only you can achieve the background process..Please Go through about Services http://developer.android.com/guide/components/services.html and you can see this also http://www.vogella.com/articles/AndroidServices/article.html both URLs will help you

instead of service Use receiver to receive the launch event
and there you can implement this code.

The approach you are taking is wrong and prone to have your app rejected from the Google Play Store (plus it may stop working).
Check this thread to see possible ways to detect wether your app went to the background or not.

Related

android studio get Activity object from service

i have an app with service that works completely background, but sometimes i need to change the content in the foreground activity , for now let's say i want to show Toast.
first i am checking if the app is opened as foreground
public boolean isForeground(String myPackage) {
ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
List<ActivityManager.RunningTaskInfo> runningTaskInfo = manager.getRunningTasks(1);
ComponentName componentInfo = runningTaskInfo.get(0).topActivity;
return componentInfo.getPackageName().equals(myPackage);
}
then i want to know what is the running activity
String PKG_Name = componentInfo.getPackageName();
this will give me the name , but what i want is to is get the object Activity ,to do something like this:
activity.runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(activity, "Hello", Toast.LENGTH_SHORT).show();
}
});
how can i do it? if not possible, is there's a way to is to send a signal or a message to the service to tell the it?
For that you have two options, if you are fine showing just a Toast and not interact with other elements, you can implement a broadcast reciever and make your custom intent with custom action,
Intent int= new Intent(); int.setAction("Your custom string here");
and then post a toast in your braodcast reciever,
OR
you can use a custom handler to interact with all the objects in foreground and activity, here's some study material for it,
https://developer.android.com/training/multiple-threads/communicate-ui

Broadcast receiver invoke when another applications a particular activity is opened

I wand a Broadcast receiver invoke when another applications a particular activity is opened in android. For example When Navigation page in Map application that installed in android phone, When opened and showing the Navigation, I want to show a Toast that display "Currently showing Navigation". So how can I achieve that?
This below code will help you to identify windo change event
public class AccessibilityEventService
extends AccessibilityService {
#Override
public void onAccessibilityEvent(AccessibilityEvent event) {
if (event.getEventType() == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED)
Log.i("op",event.getPackageName());
}
}
but it has to enabled by users from Accessibility under settings.
or You can check current top activity in a time gap using following code
ActivityManager am = (ActivityManager) this.getSystemService(ACTIVITY_SERVICE);
// get the info from the currently running task
List< ActivityManager.RunningTaskInfo > taskInfo = am.getRunningTasks(1);
Log.d("topActivity", "CURRENT Activity ::"
+ taskInfo.get(0).topActivity.getClassName());
ComponentName componentInfo = taskInfo.get(0).topActivity;
componentInfo.getPackageName();
As my understood that you need to show a toast on onRecieve Fuunction
Toast.makeText(context,"your text",2000).show();
//context is input parameter from onRecieve function

repeatedly checking whether the application is in foreground or background

I want to detect when the app comes from back ground to foreground every time.
I'm geting the state using the following code
topActivity.getPackageName().equals(context.getPackageName())
But I need to execute the code repeatedly so that I could detect every time when my app comes to foreground
It's your app. Activity always knows if it is visible or not. So make every your activity tell someone it's state. You don't need to poll app state. Check this answer.
Try this :
public static String isApplicationSentToBackground(final Context context) {
ActivityManager am = (ActivityManager) context
.getSystemService(Context.ACTIVITY_SERVICE);
List<RunningTaskInfo> tasks = am.getRunningTasks(1);
if (!tasks.isEmpty()) {
ComponentName topActivity = tasks.get(0).topActivity;
if (topActivity.getPackageName().equals(context.getPackageName())) {
return "true";
}
}
return "false";
}
Hope this helps.

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));
}

How can I detect if my Android app is displayed?

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);

Categories

Resources