Install and Launch App

I find it quite easy to install and launch an App in android, which I thought it hard.

You can install or launch a App as easy as start a Activity with some special Intent.

The following little demo will show you:

MainActivity.java

package com.slowalker.applaunch;

import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;

public class MainActivity extends Activity {

    private static final String TAG = MainActivity.class.getSimpleName();
    private static final boolean DEBUG = true;
    
    private String apkFilePath = "/mnt/sdcard/test.apk";
    private String packageName = "com.slowalker.box";
    
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        /*
        boolean result = AppLauncher.instatllApp(this, apkFilePath);
        if (DEBUG) {
            Log.d(TAG, "" + result);
        }
        */
                
        boolean result = AppLauncher.launchApp(this, packageName);
        if (DEBUG) {
            Log.d(TAG, "" + result);
        }
    }
}

AppLauncher.java

package com.slowalker.applaunch;

import java.io.File;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;

/**
 * A tool class to implement lanuch an APP.
 *
 */

public class AppLauncher {
    
    private static final String TAG = AppLauncher.class.getSimpleName();
    private static final boolean DEBUG = true;
    
    
    public static boolean instatllApp(Context context, String apkFile) {
        File apk = new File(apkFile);
        if (!apk.exists()) return false;
        Intent intent = new Intent();
        intent.setDataAndType(Uri.fromFile(apk), "application/vnd.android.package-archive");
        context.startActivity(intent);
        return true;
    }
    
    public static boolean launchApp(Context context, String packageName) {
        if (!isInstalled(packageName)) return false;
        Intent intent = context.getPackageManager().getLaunchIntentForPackage(packageName);
        context.startActivity(intent);
        return true;
    }
    
    private static boolean isInstalled(String packageName) {
        return new File("/data/data/" + packageName).exists();
    }
}
原文地址:https://www.cnblogs.com/slowalker/p/3410650.html