java – How to catch the launch event of any application?

Question:

Task: when you start any application, you need to display a Toast with the text " such and such an application has started ", and when the application is closed (via finish() , or the Back button – no difference), regardless of whether the Service this application is running or not , – again, show a Toast with the text " such-and-such application ended ".

For example, I launched the Play Market and received a Toast : "The Play market is confused ."

How to implement this? It seems you need to use Service , and then no further thoughts.

Answer:

On a good level, this is not very that and it is possible, although there are certain hacks with which you can catch the application launch event. In particular, at the time of launching the application, the OS exposes logs, approximately the following content:

05-17 13: 55: 30.586: I / ActivityManager (526): START u0 {act = android.intent.action.MAIN cat = [android.intent.category.LAUNCHER] flg = 0x10200000 cmp = com.rovio.angrybirds / com.rovio.fusion.App} from pid 818

That is, you need to log the launch of the Intent 'and android.intent.action.MAIN and extract the package (as in this case com.rovio.angrybirds )

In order to read the logs you need to have a permit

 <uses-permission android:name="android.permission.READ_LOGS" />

and read the LogCat logs in the service:

  Process logcatProc = Runtime.getRuntime().exec(new String[]{"logcat", "-d"});
  reader = new BufferedReader(new InputStreamReader(logcatProc.getInputStream()));

Then StreamReader received StreamReader

As soon as you catch the name of the starting package, it is quite simple to get the name of the program by the name of the package:

final String packageName = "my.application.package"
PackageManager packageManager= getApplicationContext().getPackageManager();
String appName = (String) packageManager.getApplicationLabel(packageManager.getApplicationInfo(packageName, PackageManager.GET_META_DATA));
Scroll to Top