Is there any way to execute a service (start or stop) only when a particular app is open? The case is that i have a "bubble" service (similar to facebook) and i only want to appear when i open the game Minecraft PE. And when i change or i open another application i want put invisible bubble. Is this possible?
Asked
Active
Viewed 57 times
1 Answers
1
Use this code.
public class CheckRunningApplicationReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context aContext, Intent anIntent) {
try {
ActivityManager am = (ActivityManager) aContext
.getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningTaskInfo> alltasks = am
.getRunningTasks(1);
for (ActivityManager.RunningTaskInfo aTask : alltasks) {
if (aTask.topActivity.getClassName().equals("com.android.phone.InCallScreen")
|| aTask.topActivity.getClassName().equals("com.android.contacts.DialtactsActivity"))
{
Toast.makeText(aContext, "Phone Call Screen.", Toast.LENGTH_LONG).show();
}
String packageName = "com.example.checkcurrentrunningapplication";
if (aTask.topActivity.getClassName().equals(
packageName + ".Main"))
{
// When opens this example screen then show a alert message
Toast.makeText(aContext, "Check Current Running Application Example Screen.",
Toast.LENGTH_LONG).show();
}
}
} catch (Throwable t) {
Log.i("THROW", "Throwable caught: "
+ t.getMessage(), t);
}
}
}
Add this in Manifest:
<receiver android:name = ".CheckRunningApplicationReceiver"/>
<uses-permission android:name="android.permission.GET_TASKS" />

Divyesh Patel
- 2,576
- 2
- 15
- 30
-
Android Studio tells me that android.permission.GET_TASKS and getRunningTasks(1) is deprecated. Is it possible that for security reasons can't access the name of the class that is currently running? Thanks. – DaveKiss Oct 26 '16 at 11:39
-
http://stackoverflow.com/questions/31156313/activitymanager-getrunningtasks-is-deprecated-android – Divyesh Patel Oct 26 '16 at 11:50