/*
 * Copyright 2012-2014 eBay Software Foundation and selendroid committers.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */
package io.selendroid.nativetests;

import io.selendroid.support.BaseAndroidTest;

import org.junit.Assert;
import org.junit.Test;


public class BackgroundAppTest extends BaseAndroidTest {

  /**
   * Requires ANDROID_HOME to be set in enviroment.
   * @throws Exception
   */
  @Test
  public void testBackgroundAppFunctionality() throws Exception {
    openStartActivity();
    driver().backgroundApp();
    String currentActivity = adbCurrentActivity();
    Assert.assertTrue(currentActivity.contains("com.android.launcher2.Launcher"));
    driver().resumeApp();
    currentActivity = adbCurrentActivity();
    Assert.assertTrue(currentActivity.contains("io.selendroid.testapp.HomeScreenActivity"));
  }

  private String adbCurrentActivity() throws Exception {
    return execCmd(System.getenv("ANDROID_HOME")+"/platform-tools/"+"adb shell dumpsys window windows | grep -E 'mCurrentFocus|mFocusedApp'");
  }

  public String execCmd(String cmd) throws java.io.IOException {
    Process proc = Runtime.getRuntime().exec(cmd);
    java.io.InputStream is = proc.getInputStream();
    java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
    String val = "";
    if (s.hasNext()) {
        val = s.next();
    }
    else {
        val = "";
    }
    return val;
  }


}

@@ -758,16 +758,40 @@
 .Test;%0A%0A
+import java.util.List;%0A%0A
 %0Apublic 
@@ -1424,23 +1424,25 @@
     
-return execCmd(
+String adbPath = 
 Syst
@@ -1494,63 +1494,268 @@
 %22adb
- shell dumpsys window windows %7C grep -E 'mCurrentFocus%7C
+%22;%0A    String output = execCmd(adbPath + %22 shell dumpsys window windows%22);%0A%0A    String activityLines = %22%22;%0A    String%5B%5D lines = output.split(%22%5Cn%22);%0A    for (int i = 0; i %3C lines.length; i++) %7B%0A      if (lines%5Bi%5D.contains(%22mCurrentFocus%22) %7C%7C lines%5Bi%5D.contains(%22
 mFoc
@@ -1765,11 +1765,88 @@
 dApp
-'
 %22)
+) %7B%0A        activityLines += lines%5Bi%5D;%0A      %7D%0A    %7D%0A%0A    return activityLines
 ;%0A  

Fix BackgroundAppTest