[Android] How to detect when the test switches to another app

I am using Appium to automatically test some Android apps. It is a great testing tool.

My question is:

Assume the package name of the target app is package_name1. When running the test, it clicks buttons and it is possible that one button click will switch to another app such as the Settings app on the device. I want to know how to detect this. One simple way I can think of is to get the package name of the current activity and compare it against package_name1, but I cannot find the API to get the package name.

Can anyone help? Thanks in advance.
Jeff

That’s precisely how we are detecting the change. We use

appium_driver.driver.current_activity

This gives you a value similar to what you would get if you executed the command

adb shell dumpsys window windows |grep Focus

and then parsed the results

1 Like

Jeff,

Any activity(as far as i know) contains two things.

  1. Package name
  2. Activity name

From this Ex: “com.Android.Settings.LaunchSettings”,
the package name is: “com.Android.Settings”
the activity name is: rest of the string following package name is activity name.
So activity name for the above ex is: “LaunchSettings”

For your question:

String strCurrentActivity=driver.currentActivity() 

Now your strCurrentActivity have this package included:

Just put a logic like:

if(strCurrentActivity.contains(package_name1)
  //Your true logic
else
 //Your false logic
1 Like

thanks guys, but my question is not resolved.

In my case, currentActivity is like this “.MainActivity”. It does not carry the package name. Any thoughts are appreciated.

1 Like

Hi @jeffchenurbana ,

A good topic raised about getting PackageName, :+1:
As far as i know there is no direct implementation for getting Package Name in Appium Api. Consider your scinario , you may have 2 possible ways,

  1. The current activities must not be the same for two apps , you can compare them and verify
  2. You can identify elements inside App and Verify.

Thanks,
Bhaskar.