android 读取APK文件信息

6,952 views

 

整理一下读取Android APK文件信息的代码,实现效果图如下:

图-1 实现获取apk文件图标,包名,版本,名称的功能

主要是实现获取apk文件图标,包名,版本,名称的功能,这一功能可以用来判断手机已安装的信息与服务器端文件信息是否一致。

1.GetAPKInfoActivity.java

package com.apkinfo.main;

import java.util.List;

import android.app.Activity;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.TextView;

public class GetAPKInfoActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String archiveFilePath = "sdcard/wandoujia/Explorer.apk";// 安装包路径
PackageManager pm = getPackageManager();
PackageInfo info = pm.getPackageArchiveInfo(archiveFilePath,
PackageManager.GET_ACTIVITIES);
if (info != null) {
ApplicationInfo appInfo = info.applicationInfo;
String appName = pm.getApplicationLabel(appInfo).toString();
String packageName = appInfo.packageName; // 得到安装包名称
String version = info.versionName; // 得到版本信息
// Toast.makeText(this,"packageName:" + packageName + ";version:" +
// version + "name:" + appName, Toast.LENGTH_LONG).show();
Drawable icon = pm.getApplicationIcon(appInfo);// 得到图标信息
ImageView image = (ImageView) findViewById(R.id.icon);
image.setImageDrawable(icon);// 显示图标
TextView tv = (TextView) findViewById(R.id.info);
tv.setText("packageName:" + packageName + ";\nversion:" + version
+ ";\nname:" + appName);
}
}

// 获取已经安装过的apk文件(该方法在本程序没有使用)
public void getInstalledAppInfo() {
PackageManager pckMan = getPackageManager();
List<PackageInfo> packs = pckMan.getInstalledPackages(0);
int count = packs.size();
for (int i = 0; i < count; i++) {
PackageInfo p = packs.get(i);
System.out.println("------------" + p.packageName.toString());
if (p.versionName == null)
continue;
}
}
}

2.main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="6dip"
android:orientation="vertical" >
<ImageView
android:id="@+id/icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/info"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello" />
</LinearLayout>

源码下载:GetAPKInfo.zip

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>