Saturday, December 12, 2015

android - How to open an app programmatically

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="16dp"
    tools:context=".MainActivity"
    android:background="#e7f2f9"
    >
    <Button
        android:id="@+id/btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Launch Kids ABC App"
        android:layout_centerInParent="true"
        />
</RelativeLayout>
MainActivity.java

package com.cfsuman.me.androidcode;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.Button;


public class MainActivity extends AppCompatActivity {
    private Context mContext;
    private Button mButton;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // Request window feature action bar
        requestWindowFeature(Window.FEATURE_ACTION_BAR);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Get the application context
        mContext = getApplicationContext();

        // Change the action bar color
        getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#FF36A6ED")));

        // Get the widgets reference from XML layout
        mButton = (Button) findViewById(R.id.btn);

        // Set a click listener for button widget
        mButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // Package name of KIDS ABC app
                String packageName="com.cfsuman.me.kidsabc";

                // Launch the app
                launchApp(packageName);
            }
        });
    }

    // Custom method to launch an app
    protected void launchApp(String packageName){
        /*
            PackageManager
                Class for retrieving various kinds of information related to the application
                packages that are currently installed on the device.
        */
        /*
            public abstract PackageManager getPackageManager ()
                Return PackageManager instance to find global package information.
        */
        // Get an instance of PackageManager
        PackageManager pm = mContext.getPackageManager();

        // Try to launch an app
        try{
            /*
                public abstract Intent getLaunchIntentForPackage (String packageName)
                    Returns a "good" intent to launch a front-door activity in a package. This is used,
                    for example, to implement an "open" button when browsing through packages.
                    The current implementation looks first for a main activity in the category
                    CATEGORY_INFO, and next for a main activity in the category CATEGORY_LAUNCHER.
                    Returns null if neither are found.

                Parameters
                    packageName : The name of the package to inspect.
                Returns
                    A fully-qualified Intent that can be used to launch the main activity in the
                    package. Returns null if the package does not contain such an activity,
                    or if packageName is not recognized.
            */
            // Initialize a new Intent
            Intent intent = pm.getLaunchIntentForPackage(packageName);

            /*
                public Intent addCategory (String category)
                    Add a new category to the intent. Categories provide additional detail about
                    the action the intent performs. When resolving an intent, only activities that
                    provide all of the requested categories will be used.

                Parameters
                    category : The desired category. This can be either one of the predefined
                    Intent categories, or a custom category in your own namespace.
                Returns
                    Returns the same Intent object, for chaining multiple calls into a single statement.
            */
            /*
                public static final String CATEGORY_LAUNCHER
                    Should be displayed in the top-level launcher.

                    Constant Value: "android.intent.category.LAUNCHER"
            */
            // Add category to intent
            intent.addCategory(Intent.CATEGORY_LAUNCHER);

            if(intent == null){
                // Throw PackageManager NameNotFoundException
                throw new PackageManager.NameNotFoundException();
            }else{
                // Start the app
                mContext.startActivity(intent);
            }
        }catch(PackageManager.NameNotFoundException e){
            /*
                public static int e (String tag, String msg)
                    Send an ERROR log message.

                Parameters
                    tag : Used to identify the source of a log message. It usually identifies the
                        class or activity where the log call occurs.
                    msg : The message you would like logged.
            */
            // Log the exception
            Log.e("Launch",e.getMessage());
        }
    }
}