Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
//License from project: Apache License 

import android.content.Context;

import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;

public class Main {
    /** Status: the specified apk is installed */
    public final static int STATUS_INSTALLED = 0;
    /** Status: the specified apk can be updated */
    public final static int STATUS_UPDATED = 1;
    /** Status: the specified apk is not installed */
    public final static int STATUS_NOT_INSTALLED = 2;

    /**
     * Get give application status: installed, not installed or update.
     * 
     * @param context Object of {@link Context}.
     * @param pkgName Package name of app.
     * @param code Application version code.
     * @return {@link #STATUS_INSTALLED}, {@link #STATUS_NOT_INSTALLED}
     *    or {@link #STATUS_UPDATED}.
     */
    public final static int getAppStatus(Context context, String pkgName, int code) {
        if (null == pkgName || null == context) {
            return STATUS_NOT_INSTALLED;
        }

        PackageInfo pkgInfo = null;
        PackageManager pm = context.getPackageManager();

        if (null == pm) {
            return STATUS_NOT_INSTALLED;
        }

        try {
            pkgInfo = pm.getPackageInfo(pkgName, 0);
            if (null == pkgInfo) {
                return STATUS_NOT_INSTALLED;
            } else {
                if (pkgInfo.versionCode == code) {
                    return STATUS_INSTALLED;
                } else if (code > pkgInfo.versionCode) {
                    return STATUS_UPDATED;
                } else {
                    return STATUS_INSTALLED;
                }
            }
        } catch (Exception e) {
            return STATUS_NOT_INSTALLED;
        }
    }
}