Sandeep Sandeep - 4 months ago 12
Android Question

Launch apps using its package name and bring it to front if it is already running

How to launch any app like messenger,chrome,etc by using its package name but if the launched is already running on the background I want it to just bring to front.I don't want to create new instance of it Is there any solution.I am testing my app on api 23 (lollipop).

Answer

Did you check this theme?

You can check running app or not

    boolean running = false;
    ActivityManager activityManager = (ActivityManager) this.getSystemService( ACTIVITY_SERVICE );
    List<RunningAppProcessInfo> procInfos = activityManager.getRunningAppProcesses();
    for(int i = 0; i < procInfos.size(); i++)
    {
        if(procInfos.get(i).processName.equals("com.example.abc")) 
        {
            running = true;
        }
    }

Then run if it is running add flag Intent.FLAG_ACTIVITY_NEW_TASK

        Intent LaunchIntent = getPackageManager().getLaunchIntentForPackage("com.example.abc");

        if (running)
           LaunchIntent .setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity( LaunchIntent );

I think you can just do it without checking, but checking is useful if you dont know exactly package`s name.

Intent LaunchIntent = getPackageManager().getLaunchIntentForPackage("com.example.abc");
LaunchIntent .setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity( LaunchIntent );
Comments