Android ddmlib: verify activity is running

I needed to find a way to verify if Android activity is running from java project, which uses ddmlib to connect to Android devices via USB.
For this purposes, I created a class, which implements IShellOutputReceiver

import com.android.ddmlib.IShellOutputReceiver;

/**
 * Created by mihails.beshkins on 16/01/14.
 */
public class ActivityRunningReceiver implements IShellOutputReceiver {
    private byte[] bytes;
    private String activityName;

    public ActivityRunningReceiver(String activityName)
    {
        this.activityName = activityName;
    }

    @Override
    public void addOutput(byte[] bytes, int i, int i2) {
        this.bytes = bytes;
    }

    @Override
    public void flush() {

    }

    @Override
    public boolean isCancelled() {

        return false;
    }

    @Override
    public String toString(){
        return new String(bytes);
    }

    public Boolean isRunning()
    {
        String s = new String(bytes);
        String[] array = s.split("\n");
        for (int i=0; i< array.length; i++)
        {
            if (array[i].contains(activityName))
                return true;
        }
        return false;
    }
}

This is needed to get output of the shell command we are executing in the following function:

private Boolean isActivityRunning(String activityName, IDevice device) throws TimeoutException, AdbCommandRejectedException, ShellCommandUnresponsiveException, IOException {
        ActivityRunningReceiver activityRunningReceiver= new ActivityRunningReceiver(activityName);
        device.executeShellCommand("dumpsys activity package com.example.test", activityRunningReceiver);
        return activityRunningReceiver.isRunning();
    }

Leave a Reply

%d bloggers like this: