Avinash Gupta Avinash Gupta - 3 months ago 10
Android Question

Get current running Activity in Android through <application> tag class

I have an Android application with 50 Activities i wont track current running activity in log-cat instead of creating ActivityManger in all activities or calling the instance object in each activity.

My thought is to create a non-activity class and append it to tag in Manifest.xml so that it should track all the activities.

Answer

You can create an Android Service and print the current activity from there. For instance, the following service will run indefinitely with a 0.7 second timeout and print the current activity to LogCat:

public class MyService extends Service {

public static final String TAG = "Background Service";

public boolean wait;
public boolean stop = false;

SharedPreferences prefs;

@Override
public IBinder onBind(Intent intent) {
    Log.i(TAG, "On bind of service");
    return null;
}

@Override
public void onDestroy() {
    stop = true;
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    (new Thread(new Runnable() {

        public void run() {
            try {
                update();
                return;
            } catch (Exception exception) {
                exception.printStackTrace();
            }
        }

    })).start();

    return super.onStartCommand(intent, flags, startId);
}

public void update() {
    List list;
    String str;

    do {
        try {
            Thread.sleep(701L);
        } catch (InterruptedException interruptedexception) {
            interruptedexception.printStackTrace();
        }

        list = ((ActivityManager) getSystemService("activity"))
                .getRunningTasks(1);
        str = ((android.app.ActivityManager.RunningTaskInfo) list.get(0)).topActivity
                .getClassName();

        Log.d(TAG, str);
    } while (!stop);

    stopSelf();
}
}

You can also pass value to stop the service after some time. If you also want to know, how to start the service, then you can do the following on the activity:

Intent intent = new Intent(this, MyService.class);
startService(intent);

and do the following to stop the service:

stopService(intent);
Comments