Is it possible to execute a service in Android only if I have an particular app that is open?

60 Views Asked by At

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?

1

There are 1 best solutions below

2
Divyesh Patel On

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" />