Android中获取apk安装包信息的方法

时间:2021-09-26 12:37:44

一、获取安装包信息

 

复制代码 代码如下:
/**
* 获取apk包的信息:版本号,名称,图标等
* @param absPath apk包的绝对路径
* @param context 
*/ 
public void apkInfo(String absPath,Context context) { 

    PackageManager pm = context.getPackageManager(); 
    PackageInfo pkgInfo = pm.getPackageArchiveInfo(absPath,PackageManager.GET_ACTIVITIES); 
    if (pkgInfo != null) { 
        ApplicationInfo appInfo = pkgInfo.applicationInfo; 
        /* 必须加这两句,不然下面icon获取是default icon而不是应用包的icon */ 
        appInfo.sourceDir = absPath; 
        appInfo.publicSourceDir = absPath; 
        String appName = pm.getApplicationLabel(appInfo).toString();// 得到应用名 
        String packageName = appInfo.packageName; // 得到包名 
        String version = pkgInfo.versionName; // 得到版本信息 
        /* icon1和icon2其实是一样的 */ 
        Drawable icon1 = pm.getApplicationIcon(appInfo);// 得到图标信息 
        Drawable icon2 = appInfo.loadIcon(pm); 
        String pkgInfoStr = String.format("PackageName:%s, Vesion: %s, AppName: %s", packageName, version, appName); 
        Log.i(TAG, String.format("PkgInfo: %s", pkgInfoStr)); 
    } 
}

 

二、在APK安装的时候,我们可以获取安装包、版本、包名等信息。

 

复制代码 代码如下:


public class TestActivity extends Activity {
 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);
  String archiveFilePath="sdcard/jb51.net.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(TestActivity.this, , Toast.LENGTH_LONG).show();
     Drawable icon = pm.getApplicationIcon(appInfo);//得到图标信息
     TextView tv = (TextView)findViewById(R.id.tv);
     tv.setText("appName:"+appName+"---packageName:"+packageName);
     //显示图标
     ImageView tu=(ImageView)findViewById(R.id.imageView1);
     tu.setBackgroundDrawable(icon);
    }
   }

 

  }
 }

}