获取App应用信息

??安卓开发一般都需要进行apk的更新管理,常用操作老司机已为你封装完毕,经常有小伙伴问怎么进行管理,那我告诉你,你可以用这份工具进行管理,具体可以查看源码,现在为你开车,Demo传送门

站点

获取App应用版本信息 → AppApplicationMgr

getAppName             : 获取本地apk的名称
getVersionName         : 获取本地Apk版本名称
getVersionCode         : 获取本地Apk版本号
getMetaData            : 根据key获取xml中Meta的值
getAppIcon             : 获取应用图标
getAppFirstInstallTime : 获取应用第一次安装日期
getAppLastUpdateTime   : 获取应用更新日期
getAppSize             : 获取应用大小
getAppApk              : 获取应用apk文件
getAppInstaller        : 获取应用的安装市场
getAppSign             : 获取应用签名
getAppTargetSdkVersion : 获取应用兼容sdk
getAppUid              : 获取应用uid
getNumCores            : 获取Cpu内核数
getRootPermission      : 获得root权限
getAppPermissions      : 获取应用的所有权限
hasPermission          : 是否有权限
isInstalled            : 应用是否安装
installApk             : 安装应用
uninstallApk           : 卸载应用
isSystemApp            : 是否是系统应用
isServiceRunning       : 服务是否在运行
stopRunningService     : 停止服务
killProcesses          : 结束进程
runScript              : 运行脚本
runApp                 : 启动应用
getPackageName         : 获得包名
getApplicationMetaData : 获取application层级的metadata

具体路线

@SuppressWarnings("rawtypes")
public class AppApplicationMgr {

/**
 * 获取本地apk的名称
 * @param context 上下文
 * @return String
 */
public static String getAppName(Context context) {
    try {
        PackageManager e = context.getPackageManager();
        PackageInfo packageInfo = e.getPackageInfo(context.getPackageName(), 0);
        int labelRes = packageInfo.applicationInfo.labelRes;
        return context.getResources().getString(labelRes);
    } catch (NameNotFoundException var4) {
        var4.printStackTrace();
        return "unKnown";
    }
}

/**
 * 获取本地Apk版本名称
 * @param context 上下文
 * @return String
 */
public static String getVersionName(Context context) {
    String verName = "";
    try {
        verName = context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionName;
    } catch (NameNotFoundException e) {
        AppLogMessageMgr.e("AppApplicationMgr-->>getVerName()", e.getMessage() + "获取本地Apk版本名称失败!");
        e.printStackTrace();
    }
    return verName;
}

/**
 * 获取本地Apk版本号
 * @param context 上下文
 * @return int
 */
public static int getVersionCode(Context context) {
    int verCode = -1;
    try {
        verCode = context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionCode;
    } catch (NameNotFoundException e) {
        AppLogMessageMgr.e("AppApplicationMgr-->>getVerCode()", e.getMessage() + "获取本地Apk版本号失败!");
        e.printStackTrace();
    }
    return verCode;
}

/**
 * 根据key获取xml中Meta的值
 * @param context 上下文
 * @param key
 * @return
 */
public static String getMetaData(Context context, String key) {
    String value = "";

    try {
        ApplicationInfo e = context.getPackageManager().getApplicationInfo(context.getPackageName(), 128);
        if(null != e) {
            Bundle metaData = e.metaData;
            if(null != metaData) {
                value = metaData.getString(key);
                if(null == value || value.length() == 0) {
                    value = "";
                }
            }
        }
    } catch (NameNotFoundException var5) {
        var5.printStackTrace();
    }

    return value;
}

/**
 * 获取应用图标
 * @param context
 * @param packageName
 * @return
 */
public static Drawable getAppIcon(Context context, String packageName) {
    PackageManager pm = context.getPackageManager();
    Drawable appIcon = null;
    try {
        ApplicationInfo applicationInfo = pm.getApplicationInfo(packageName, 0);
        appIcon = applicationInfo.loadIcon(pm);
    } catch (PackageManager.NameNotFoundException e) {
        e.printStackTrace();
    }
    return appIcon;
}

/**
 * 获取应用第一次安装日期
 * @param context
 * @param packageName
 * @return
 */
public static long getAppFirstInstallTime(Context context, String packageName) {
    long lastUpdateTime = 0;
    try {
        PackageInfo packageInfo = context.getPackageManager().getPackageInfo(packageName, 0);
        lastUpdateTime = packageInfo.firstInstallTime;
    } catch (PackageManager.NameNotFoundException e) {
        e.printStackTrace();
    }
    return lastUpdateTime;
}

/**
 * 获取应用更新日期
 * @param context
 * @param packageName
 * @return
 */
public static long getAppLastUpdateTime(Context context, String packageName) {
    long lastUpdateTime = 0;
    try {
        PackageInfo packageInfo = context.getPackageManager().getPackageInfo(packageName, 0);
        lastUpdateTime = packageInfo.lastUpdateTime;
    } catch (PackageManager.NameNotFoundException e) {
        e.printStackTrace();
    }
    return lastUpdateTime;
}

/**
 * 获取应用大小
 * @param context
 * @param packageName
 * @return
 */
public static long getAppSize(Context context, String packageName) {
    long appSize = 0;
    try {
        ApplicationInfo applicationInfo = context.getPackageManager().getApplicationInfo(packageName, 0);
        appSize = new File(applicationInfo.sourceDir).length();
    } catch (PackageManager.NameNotFoundException e) {
        e.printStackTrace();
    }
    return appSize;
}

/**
 * 获取应用apk文件
 * @param context
 * @param packageName
 * @return
 */
public static String getAppApk(Context context, String packageName) {
    String sourceDir = null;
    try {
        ApplicationInfo applicationInfo = context.getPackageManager().getApplicationInfo(packageName, 0);
        sourceDir = applicationInfo.sourceDir;
    } catch (PackageManager.NameNotFoundException e) {
        e.printStackTrace();
    }
    return sourceDir;
}

/**
 * 获取应用的安装市场
 * @param context
 * @param packageName
 * @return
 */
public static String getAppInstaller(Context context, String packageName) {
    return context.getPackageManager().getInstallerPackageName(packageName);
}

/**
 * 获取应用签名
 * @param context
 * @param packageName
 * @return
 */
public static String getAppSign(Context context, String packageName) {
    try {
        PackageInfo pis = context.getPackageManager().getPackageInfo(packageName, PackageManager.GET_SIGNATURES);
        return hexdigest(pis.signatures[0].toByteArray());
    } catch (PackageManager.NameNotFoundException e) {
        throw new RuntimeException(AppApplicationMgr.class.getName() + "the " + packageName + "‘s application not found");
    }
}

public static String hexdigest(byte[] paramArrayOfByte) {
    final char[] hexDigits = {48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 97, 98, 99, 100, 101, 102};
    try {
        MessageDigest localMessageDigest = MessageDigest.getInstance("MD5");
        localMessageDigest.update(paramArrayOfByte);
        byte[] arrayOfByte = localMessageDigest.digest();
        char[] arrayOfChar = new char[32];
        for (int i = 0, j = 0; ; i++, j++) {
            if (i >= 16) {
                return new String(arrayOfChar);
            }
            int k = arrayOfByte[i];
            arrayOfChar[j] = hexDigits[(0xF & k >>> 4)];
            arrayOfChar[++j] = hexDigits[(k & 0xF)];
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return "";
}

/**
 * 获取应用兼容sdk
 * @param context
 * @param packageName
 * @return
 */
public static int getAppTargetSdkVersion(Context context, String packageName) {
    try {
        PackageInfo packageInfo = context.getPackageManager().getPackageInfo(packageName, 0);
        ApplicationInfo applicationInfo = packageInfo.applicationInfo;
        return applicationInfo.targetSdkVersion;
    } catch (PackageManager.NameNotFoundException e) {
        e.printStackTrace();
        return 0;
    }
}

/**
 * 获取应用uid
 * @param context
 * @param packageName
 * @return
 */
public static int getAppUid(Context context, String packageName) {
    try {
        PackageInfo packageInfo = context.getPackageManager().getPackageInfo(packageName, 0);
        ApplicationInfo applicationInfo = packageInfo.applicationInfo;
        return applicationInfo.uid;
    } catch (PackageManager.NameNotFoundException e) {
        e.printStackTrace();
        return 0;
    }
}

/**
 * 获取Cpu内核数
 * @return
 */
public static int getNumCores() {
    try {
        File dir = new File("/sys/devices/system/cpu/");
        File[] files = dir.listFiles(new FileFilter() {

            @Override
            public boolean accept(File pathname) {
                return Pattern.matches("cpu[0-9]", pathname.getName());
            }

        });
        return files.length;
    } catch (Exception e) {
        e.printStackTrace();
        return 1;
    }
}

/**
 * 获得root权限
 * @param context
 * @return
 */
public static boolean getRootPermission(Context context) {
    String packageCodePath = context.getPackageCodePath();
    Process process = null;
    DataOutputStream os = null;
    try {
        String cmd = "chmod 777 " + packageCodePath;
        process = Runtime.getRuntime().exec("su");
        os = new DataOutputStream(process.getOutputStream());
        os.writeBytes(cmd + "\n");
        os.writeBytes("exit\n");
        os.flush();
        process.waitFor();
    } catch (Exception e) {
        return false;
    } finally {
        try {
            if (os != null) {
                os.close();
            }
            process.destroy();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    return true;
}

/**
 * 获取应用的所有权限
 * @param context
 * @param packname
 * @return
 */
public static String[] getAppPermissions(Context context, String packname) {
    String[] requestedPermissions = null;
    try {
        PackageInfo info = context.getPackageManager().getPackageInfo(packname, PackageManager.GET_PERMISSIONS);
        requestedPermissions = info.requestedPermissions;
    } catch (PackageManager.NameNotFoundException e) {
        e.printStackTrace();
    }
    return requestedPermissions;
}

/**
 * 是否有权限
 * @param context
 * @param permission
 * @return
 */
public static boolean hasPermission(Context context, String permission) {
    if (context != null && !TextUtils.isEmpty(permission)) {
        try {
            PackageManager packageManager = context.getPackageManager();
            if (packageManager != null) {
                if (PackageManager.PERMISSION_GRANTED == packageManager.checkPermission(permission, context
                    .getPackageName())) {
                    return true;
                }
                Log.d("AppUtils", "Have you  declared permission " + permission + " in AndroidManifest.xml ?");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
    return false;
}

/**
 * 应用是否安装
 * @param context
 * @param packageName
 * @return
 */
public static boolean isInstalled(Context context, String packageName) {
    boolean installed = false;
    if (TextUtils.isEmpty(packageName)) {
        return false;
    }
    List<ApplicationInfo> installedApplications = context.getPackageManager().getInstalledApplications(0);
    for (ApplicationInfo in : installedApplications) {
        if (packageName.equals(in.packageName)) {
            installed = true;
            break;
        } else {
            installed = false;
        }
    }
    return installed;
}

/**
 * 安装应用
 * @param context
 * @param filePath
 * @return
 */
public static boolean installApk(Context context, String filePath) {
    File file = new File(filePath);
    if (!file.exists() || !file.isFile() || file.length() <= 0) {
        return false;
    }
    Intent i = new Intent(Intent.ACTION_VIEW);
    i.setDataAndType(Uri.parse("file://" + filePath), "application/vnd.android.package-archive");
    i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    context.startActivity(i);
    return true;
}

/**
 * 卸载应用
 * @param context
 * @param packageName
 * @return
 */
public static boolean uninstallApk(Context context, String packageName) {
    if (TextUtils.isEmpty(packageName)) {
        return false;
    }
    Intent i = new Intent(Intent.ACTION_DELETE, Uri.parse("package:" + packageName));
    i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    context.startActivity(i);
    return true;
}

/**
 * 是否是系统应用
 * @param context
 * @param packageName
 * @return
 */
public static boolean isSystemApp(Context context, String packageName) {
    boolean isSys = false;
    PackageManager pm = context.getPackageManager();
    try {
        ApplicationInfo applicationInfo = pm.getApplicationInfo(packageName, 0);
        if (applicationInfo != null && (applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) > 0) {
            isSys = true;
        }
    } catch (PackageManager.NameNotFoundException e) {
        e.printStackTrace();
        isSys = false;
    }
    return isSys;
}

/**
 * 服务是否在运行
 * @param context
 * @param className
 * @return
 */
public static boolean isServiceRunning(Context context, String className) {
    boolean isRunning = false;
    ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
    List<RunningServiceInfo> servicesList = activityManager.getRunningServices(Integer.MAX_VALUE);
    for (RunningServiceInfo si : servicesList) {
        if (className.equals(si.service.getClassName())) {
            isRunning = true;
        }
    }
    return isRunning;
}

/**
 * 停止服务
 * @param context
 * @param className
 * @return
 */
public static boolean stopRunningService(Context context, String className) {
    Intent intent_service = null;
    boolean ret = false;
    try {
        intent_service = new Intent(context, Class.forName(className));
    } catch (Exception e) {
        e.printStackTrace();
    }
    if (intent_service != null) {
        ret = context.stopService(intent_service);
    }
    return ret;
}

/**
 * 结束进程
 * @param context
 * @param pid
 * @param processName
 */
public static void killProcesses(Context context, int pid, String processName) {
    ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
    String packageName;
    try {
        if (!processName.contains(":")) {
            packageName = processName;
        } else {
            packageName = processName.split(":")[0];
        }
        activityManager.killBackgroundProcesses(packageName);
        Method forceStopPackage = activityManager.getClass().getDeclaredMethod("forceStopPackage", String.class);
        forceStopPackage.setAccessible(true);
        forceStopPackage.invoke(activityManager, packageName);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

/**
 * 运行脚本
 * @param script
 * @return
 */
public static String runScript(String script) {
    String sRet;
    try {
        final Process m_process = Runtime.getRuntime().exec(script);
        final StringBuilder sbread = new StringBuilder();
        Thread tout = new Thread(new Runnable() {
            public void run() {
                BufferedReader bufferedReader = new BufferedReader(
                    new InputStreamReader(m_process.getInputStream()),
                    8192);
                String ls_1;
                try {
                    while ((ls_1 = bufferedReader.readLine()) != null) {
                        sbread.append(ls_1).append("\n");
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    try {
                        bufferedReader.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        tout.start();

        final StringBuilder sberr = new StringBuilder();
        Thread terr = new Thread(new Runnable() {
            public void run() {
                BufferedReader bufferedReader = new BufferedReader(
                    new InputStreamReader(m_process.getErrorStream()),
                    8192);
                String ls_1;
                try {
                    while ((ls_1 = bufferedReader.readLine()) != null) {
                        sberr.append(ls_1).append("\n");
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    try {
                        bufferedReader.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        terr.start();

        m_process.waitFor();
        while (tout.isAlive()) {
            Thread.sleep(50);
        }
        if (terr.isAlive())
            terr.interrupt();
        String stdout = sbread.toString();
        String stderr = sberr.toString();
        sRet = stdout + stderr;
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
    return sRet;
}

/**
 * 启动应用
 * @param context
 * @param packagename
 */
public static void runApp(Context context, String packagename) {
    context.startActivity(new Intent(context.getPackageManager().getLaunchIntentForPackage(packagename)));
}

// /**
// * 获得当前版本信息
// * @param keyValues key信息
// * @return RequestParams
// */
// public static RequestParams getRequestParams(HashMap<String,String> keyValues){
// RequestParams params = new RequestParams();
// Iterator iterator = keyValues.entrySet().iterator();
// while(iterator.hasNext()){
// Map.Entry entry = (Map.Entry) iterator.next();
// Object key = entry.getKey();
// params.put((String) key, entry.getValue().toString());
// }
// return params;
// }

/**
 * 获得包名
 *
 * @param context 上下文
 * @return 包名
 */
public static String getPackageName(Context context) {
    try {
        return context.getPackageManager().getPackageInfo(context.getPackageName(), 0).packageName;
    } catch (PackageManager.NameNotFoundException e) {
        e.printStackTrace();
    }
    return null;
}

/**
 * 获取application层级的metadata
 *
 * @param context 上下文
 * @param key     key
 * @return value
 */
public static String getApplicationMetaData(Context context, String key) {
    try {
        Bundle metaData = context.getPackageManager().getApplicationInfo(context.getPackageName(), PackageManager.GET_META_DATA).metaData;
        return metaData.get(key).toString();
    } catch (PackageManager.NameNotFoundException e) {
        e.printStackTrace();
    }
    return null;
}

/**
 * 获得应用申明的所有权限列表
 * @param context 上下文
 * @return 获得应用申明的所有权限列表
 */
public static List<String> getPermissions(Context context){
    List<String> permissions=new ArrayList<String>();
    try {
        PackageInfo packageInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), PackageManager.GET_PERMISSIONS);
        permissions.addAll(Arrays.asList(packageInfo.requestedPermissions));

    } catch (PackageManager.NameNotFoundException e) {
        e.printStackTrace();
    }
    return permissions;
}

}

终点站

??好了,终点站到了,如果对本次旅途满意的话,请给五星好评哦,没关注的小伙伴轻轻点个上方的关注,毕竟老司机牺牲了很多时间才换来这么一份工具类,如果该工具类依赖其他工具类,都可以在我的史上最全的常用开发工具类收集(持续更新中)中找到。

时间: 2024-10-12 07:03:43

获取App应用信息的相关文章

获取app崩溃信息的途径 iOS

获取崩溃日志的几种方法: 1.当用户抱怨闪退时,你可以要求他让设备与iTunes同步,设备与电脑上的iTunes Store同步后,会将崩溃日志保存在电脑上(路径:Mac OS X:~/Library/Logs/CrashReporter/MobileDevice/)到上述位置把崩溃日志下载下来,然后通过电子邮件发送给你:用这个方法获取崩溃日志时,你必需尽量获取用户设备生成的所有崩溃日志.因为崩溃日志越多,就越容易诊断问题所在. 2.如果你装了Xcode,也能很容易通过Xcode从你的设备上获得

获取app安装信息私有api

@class LSApplicationProxy, NSArray, NSDictionary, NSProgress, NSString, NSURL, NSUUID; @interface LSApplicationProxy : LSResourceProxy <NSSecureCoding> { NSArray *_UIBackgroundModes; NSString *_applicationType; NSArray *_audioComponents; unsigned in

iOS 获取APP相关信息 私有API

/* Generated by RuntimeBrowser Image: /System/Library/Frameworks/MobileCoreServices.framework/MobileCoreServices */ @interface LSApplicationWorkspace : NSObject // Image: /System/Library/Frameworks/MobileCoreServices.framework/MobileCoreServices + (i

Android-获取app包信息异常

public PackageInfo getPackageArchiveInfo (String archiveFilePath, int flags) 获取app包信息,传入文件名,返回的PackageInfo结构如为空,不可访问,出现Null指针: 说明app包可能是无法解析的,有问题: 并不是代码出的错.

android 安卓APP获取手机设备信息和手机号码的代码示例

下面我从安卓开发的角度,简单写一下如何获取手机设备信息和手机号码 准备条件:一部安卓手机.手机SIM卡确保插入手机里.eclipse ADT和android-sdk开发环境 第一步:新建一个android工程(JinshanTest), 并需要在工程的AndroidManifest.xml文件中,添加权限 <uses-permission android:name="android.permission.READ_PHONE_STATE"/> 图例: 第二步:新建一个工具类

iOS获取app图标和启动图片名字(AppIcon and LaunchImage&#39;s name)

在某种场景下,可能我们需要获取app的图标名称和启动图片的名称.比如说app在前台时,收到了远程通知但是通知栏是不会有通知提醒的,这时我想做个模拟通知提示,需要用到icon名称:再比如在加载某个控制器时,想设置该控制器的背景图片为启动图片,需要用到启动图片名称. 而事实上icon图片放在系统AppIcon文件夹里,启动图片放在系统LaunchImage文件夹里,取这些图片的名称和其他一般资源图片名称不一样. 为了方便举例子,咱们先简单粗暴点 假设当前项目只支持iPhone设备,并且只支持竖屏:而

MonkeyRunner 之如何获取APP的Package Name和Activity Name

MonkeyRunner 之如何获取APP的Package Name和Activity Name   最近尝试学习使用monkeyrunner进行Android自动化测试,一开始均是使用点击屏幕坐标的方法来运行应用程序,可是点击屏幕坐标的方法比较麻烦,且通用性差.通过度娘我知道可以使用device.startActivity("package name /activity")这个函数来直接启用安装在手机中的app,可是如何获得activity却成了关键,现将获取activity的方法总

.Net Web Api——获取客户端浏览器信息

第一次接触到web api,发现这个东西是REST风格的:---- 微软的web api是在vs2012上的mvc4项目绑定发行的,它提出的web api是完全基于RESTful标准的,完全不同于之前的(同是SOAP协议的)wcf和webService,它是简单,代码可读性强的,上手快的,如果要拿它和web服务相比,我会说,它的接口更标准,更清晰,没有混乱的方法名称,有的只有几种标准的请求,如get,post,put,delete等,它们分别对应的几个操作,下面讲一下: GET:生到数据列表(默

获取应用程序信息.h

////  获取应用程序信息.h//  IOS笔记// 一般会用来判断是否有新版本.是否需要强制更新 iOS的版本号,一个叫做Version,一个叫做Build,这两个值都可以在Xcode 中选中target,点击“Summary”后看到. Version在plist文件中的key是“CFBundleShortVersionString”,和AppStore上的版本号保持一致,Build在plist中的key是“CFBundleVersion”,代表build的版本号,该值每次build之后都应