关于PackageInfo、ApplicationInfo、ActivityInfo、ResolveInfo四种信息类的区别之我见

来源:互联网 发布:手机sd卡数据恢复 编辑:程序博客网 时间:2024/05/17 07:32

关于PackageInfo、ApplicationInfo、ActivityInfo、ResolveInfo四种信息类的区别之我见

2014年09月05日 ⁄ 综合 ⁄ 共 2871字 ⁄ 字号 小 中 大 ⁄ 评论关闭

PackageInfo:

获得方法:

[java] view plain copy
 print?
  1. PackageManager packageManager = context.getPackageManager();//返回packagemanager实例来找到全球包装信息(来自百度翻译)  
  2.         List<PackageInfo> allPackageInfos = packageManager  
  3.                 .getInstalledPackages(packageManager.GET_UNINSTALLED_PACKAGES  
  4.                         | packageManager.GET_ACTIVITIES);// 初始化时先要得到当前的所有进程  

特点:

常用字段:
           public String    packageName                   包名
           public ActivityInfo[]     activities                   所有<activity>节点信息
           public ApplicationInfo applicationInfo       <application>节点信息,只有一个
           public ActivityInfo[]    receivers                  所有<receiver>节点信息,多个
           public ServiceInfo[]    services                  所有<service>节点信息 ,多个

通过 PackageInfo  获取具体信息方法:
包名获取方法:packageInfo.packageName
icon获取获取方法:packageManager.getApplicationIcon(applicationInfo)
应用名称获取方法:packageManager.getApplicationLabel(applicationInfo)
使用权限获取方法:packageManager.getPackageInfo(packageName,PackageManager.GET_PERMISSIONS).requestedPermissions

ApplicationInfo:

获得方法:

[java] view plain copy
 print?
  1. List<PackageInfo> sysPackageInfos = new ArrayList<PackageInfo>();// 定义系统安装软件信息包  
  2.         for (PackageInfo packageInfo : allPackageInfos)// 循环取出所有软件信息  
  3.         {  
  4.             ApplicationInfo applicationInfo = packageInfo.applicationInfo;// 得到每个软件信息  
  5.               
  6.         }  

特点:

ApplicationInfo是从一个特定的应用得到的信息。这些信息是从相对应的Androdimanifest.xml的< application>标签中收集到的。
ApplicationInfo类 继承自  PackageItemInfo
         说明:获取一个特定引用程序中<application>节点的信息。
         字段说明:
      flags字段: FLAG_SYSTEM 系统应用程序
                   FLAG_EXTERNAL_STORAGE 表示该应用安装在sdcard中
         常用方法继承至PackageItemInfo类中的loadIcon()和loadLabel()

ResolveInfo:

获得方法:

[java] view plain copy
 print?
  1. Intent startIntent = new Intent(Intent.ACTION_MAIN, null);//为本startIntent设置行为为ACTION_MAIN  
  2.         startIntent.addCategory(Intent.CATEGORY_LAUNCHER);//为本startIntent设置启动方式为LAUNCHER  
  3.         startIntent.setPackage(packageInfo.getPkgName());//为本startIntent设置包名为packageInfo.getPkgName()  
  4.         //以startIntent为查询条件查询出需要启动的App的信息  
  5.         //功能 :返回给定条件的所有ResolveInfo对象(本质上是Activity),集合对象  
  6.         List<ResolveInfo> startInfoList = SoftManagementActivity.this  
  7.                 .getPackageManager().queryIntentActivities(startIntent, 0);  
  8.         //如果startInfoList的长度小于1,则返回  
  9.         if (startInfoList.size() < 1)  
  10.         {  
  11.             return;  
  12.         }  
  13.         //startInfoList中一般第一条就是启程App的信息  
  14.         ResolveInfo startInfo = startInfoList.iterator().next();  
  15.           

特点:

ResolveInfo这个类是通过解析一个与IntentFilter相对应的intent得到的信息。它部分地对应于从AndroidManifest.xml的< intent>标签收集到的信息。

ResolveInfo类        说明:根据<intent>节点来获取其上一层目录的信息,通常是<activity>、<receiver>、<service>节点信息。       常用字段:             public  ActivityInfo  activityInfo     获取 ActivityInfo对象,即<activity>或<receiver >节点信息             public ServiceInfo   serviceInfo     获取 ServiceInfo对象,即<activity>节点信息       常用方法:              Drawable loadIcon(PackageManager pm)             获得当前应用程序的图像             CharSequence loadLabel(PackageManager pm)  获得当前应用程序的label

通过ResolveInfo 获取具体信息方法:包名获取方法:resolve.activityInfo.packageNameicon获取获取方法:resolve.loadIcon(packageManager)应用名称获取方法:resolve.loadLabel(packageManager).toString()

ActivityInfo:

获得方法:

[java] view plain copy
 print?
  1. ActivityInfo activityInfo = startInfo.activityInfo;  

特点:

ActivityInfo类  继承自 PackageItemInfo
          说明: 获得应用程序中<activity/>或者 <receiver />节点的信息 。我们可以通过它来获取我们设置的任何属性,包括
      theme 、launchMode、launchmode等
             常用方法继承至PackageItemInfo类中的loadIcon()和loadLabel() 



1.PackageInfo、ResolveInfo

  PackageItemInfo:包含了一些信息的基类,

    它的直接子类有:

      ApplicationInfo、 ComponentInfo、InstrumentationInfo、PermissionGroupInfo、PermissionInfo。

   它的间接子类有:

      ActivityInfo、ProviderInfo、ServiceInfo。这个类包含的信息对于所有包中项目是平等的。这些Package items是被Package manager所持有的。

    

    这个类提供了属性:label、icon和meta-data。这个类的意图不是被自己调用。它只是简单分享被PackageManager返回的所有items之间的普通定义。比如,它自己并不实现Parcelable接口,但却帮助实现了Parcelable的子类ResolveInfo提供了方便的方法。

    ApplicationInfo是从一个特定的应用得到的信息。这些信息是从相对应的AndrodiManifest.xml的<application>标签中收集到的。
  ResolveInfo这个类是通过解析一个与IntentFilter相对应的intent得到的信息。它部分地对应于从AndroidManifest.xml的<intent>标签收集到的信息。


    PackageManager这个类是用来返回各种的关联了当前已装入设备了的应用的包的信息。你可以通过getPacageManager来得到这个类。
  ApplicationInfo与ResolveInfo比较:前者能够得到Icon、Label、meta-data、description。后者只能得到Icon、Label。


   具体应用实例:

   通过调用PackageManager的方法可以得到两种不同的信息:
  PackageManager packageManager = getPackageManager();

  List<ApplicationInfo> applicationList =packageManager.getInstalledApplications(PackageManager.GET_UNINSTALLED_PACKAGES);

    它是通过解析AndroidManifest.xml<application>标签中得到的,所以它能得到所有的app。


  Intent intent = new Intent(Intent.ACTION_MAIN, null);


  intent.addCategory(Intent.CATEGORY_LAUNCHER);


    //通过Intent查找相关的Activity,更准确
  List<ResolveInfo> resolveList = packageManager.queryIntentActivities(intent, 0);


  //它是通过解析<Intent-filter>标签得到
  <action Android:name=”android.intent.action.MAIN”/>
  <action android:name=”android.intent.category.LAUNCHER”/>


    一句话吧:

    通过 PackageInfo 获取具体信息方法:

    包名获取方法:packageInfo.packageName
    icon获取获取方法:packageManager.getApplicationIcon(applicationInfo)
    应用名称获取方法:packageManager.getApplicationLabel(applicationInfo)
    使用权限获取方法:packageManager.getPackageInfo(packageName,PackageManager.GET_PERMISSIONS).requestedPermissions

    通过 ResolveInfo 获取具体信息方法:

    包名获取方法:resolve.activityInfo.packageName
    icon获取获取方法:resolve.loadIcon(packageManager)
    应用名称获取方法:resolve.loadLabel(packageManager).toString()


    

[java] view plaincopyprint?在CODE上查看代码片派生到我的代码片
  1. // 获取应用程序下所有Activity  
  2. public static ArrayList<String> getActivities(Context ctx) {  
  3.       ArrayList<String> result = new ArrayList<String>();  
  4.       Intent intent = new Intent(Intent.ACTION_MAIN, null);  
  5.       intent.setPackage(ctx.getPackageName());  
  6.       for (ResolveInfo info : ctx.getPackageManager().queryIntentActivities(intent, 0)) {  
  7.           result.add(info.activityInfo.name);  
  8.       }  
  9.       return result;  
  10.   }  


/*

 * Copyright (C) 2007 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */


package android.content.pm;


import android.content.ComponentName;
import android.content.IntentFilter;
import android.graphics.drawable.Drawable;
import android.os.Parcel;
import android.os.Parcelable;
import android.text.TextUtils;
import android.util.Printer;
import android.util.Slog;


import java.text.Collator;
import java.util.Comparator;


/**
 * Information that is returned from resolving an intent
 * against an IntentFilter. This partially corresponds to
 * information collected from the AndroidManifest.xml's
 * &lt;intent&gt; tags.
 */
public class ResolveInfo implements Parcelable {
    private static final String TAG = "ResolveInfo";


    /**
     * The activity or broadcast receiver that corresponds to this resolution
     * match, if this resolution is for an activity or broadcast receiver.
     * Exactly one of {@link #activityInfo}, {@link #serviceInfo}, or
     * {@link #providerInfo} will be non-null.
     */
    public ActivityInfo activityInfo;
    
    /**
     * The service that corresponds to this resolution match, if this resolution
     * is for a service. Exactly one of {@link #activityInfo},
     * {@link #serviceInfo}, or {@link #providerInfo} will be non-null.
     */
    public ServiceInfo serviceInfo;


    /**
     * The provider that corresponds to this resolution match, if this
     * resolution is for a provider. Exactly one of {@link #activityInfo},
     * {@link #serviceInfo}, or {@link #providerInfo} will be non-null.
     */
    public ProviderInfo providerInfo;


    /**
     * The IntentFilter that was matched for this ResolveInfo.
     */
    public IntentFilter filter;
    
    /**
     * The declared priority of this match.  Comes from the "priority"
     * attribute or, if not set, defaults to 0.  Higher values are a higher
     * priority.
     */
    public int priority;
    
    /**
     * Order of result according to the user's preference.  If the user
     * has not set a preference for this result, the value is 0; higher
     * values are a higher priority.
     */
    public int preferredOrder;
    
    /**
     * The system's evaluation of how well the activity matches the
     * IntentFilter.  This is a match constant, a combination of
     * {@link IntentFilter#MATCH_CATEGORY_MASK IntentFilter.MATCH_CATEGORY_MASK}
     * and {@link IntentFilter#MATCH_ADJUSTMENT_MASK IntentFiler.MATCH_ADJUSTMENT_MASK}.
     */
    public int match;
    
    /**
     * Only set when returned by
     * {@link PackageManager#queryIntentActivityOptions}, this tells you
     * which of the given specific intents this result came from.  0 is the
     * first in the list, < 0 means it came from the generic Intent query.
     */
    public int specificIndex = -1;
    
    /**
     * This filter has specified the Intent.CATEGORY_DEFAULT, meaning it
     * would like to be considered a default action that the user can
     * perform on this data.
     */
    public boolean isDefault;
    
    /**
     * A string resource identifier (in the package's resources) of this
     * match's label.  From the "label" attribute or, if not set, 0.
     */
    public int labelRes;
    
    /**
     * The actual string retrieve from <var>labelRes</var> or null if none
     * was provided.
     */
    public CharSequence nonLocalizedLabel;
    
    /**
     * A drawable resource identifier (in the package's resources) of this
     * match's icon.  From the "icon" attribute or, if not set, 0.
     */
    public int icon;


    /**
     * Optional -- if non-null, the {@link #labelRes} and {@link #icon}
     * resources will be loaded from this package, rather than the one
     * containing the resolved component.
     */
    public String resolvePackageName;


    /**
     * @hide Target comes from system process?
     */
    public boolean system;


    private ComponentInfo getComponentInfo() {
        if (activityInfo != null) return activityInfo;
        if (serviceInfo != null) return serviceInfo;
        if (providerInfo != null) return providerInfo;
        throw new IllegalStateException("Missing ComponentInfo!");
    }


    /**
     * Retrieve the current textual label associated with this resolution.  This
     * will call back on the given PackageManager to load the label from
     * the application.
     * 
     * @param pm A PackageManager from which the label can be loaded; usually
     * the PackageManager from which you originally retrieved this item.
     * 
     * @return Returns a CharSequence containing the resolutions's label.  If the
     * item does not have a label, its name is returned.
     */
    public CharSequence loadLabel(PackageManager pm) {
        if (nonLocalizedLabel != null) {
            return nonLocalizedLabel;
        }
        CharSequence label;
        if (resolvePackageName != null && labelRes != 0) {
            label = pm.getText(resolvePackageName, labelRes, null);
            if (label != null) {
                return label.toString().trim();
            }
        }
        ComponentInfo ci = getComponentInfo();
        ApplicationInfo ai = ci.applicationInfo;
        if (labelRes != 0) {
            label = pm.getText(ci.packageName, labelRes, ai);
            if (label != null) {
                return label.toString().trim();
            }
        }


        CharSequence data = ci.loadLabel(pm);
        // Make the data safe
        if (data != null) data = data.toString().trim();
        return data;
    }
    
    /**
     * Retrieve the current graphical icon associated with this resolution.  This
     * will call back on the given PackageManager to load the icon from
     * the application.
     * 
     * @param pm A PackageManager from which the icon can be loaded; usually
     * the PackageManager from which you originally retrieved this item.
     * 
     * @return Returns a Drawable containing the resolution's icon.  If the
     * item does not have an icon, the default activity icon is returned.
     */
    public Drawable loadIcon(PackageManager pm) {
        Drawable dr;
        if (resolvePackageName != null && icon != 0) {
            dr = pm.getDrawable(resolvePackageName, icon, null);
            if (dr != null) {
                return dr;
            }
        }
        ComponentInfo ci = getComponentInfo();
        ApplicationInfo ai = ci.applicationInfo;
        if (icon != 0) {
            dr = pm.getDrawable(ci.packageName, icon, ai);
            if (dr != null) {
                return dr;
            }
        }
        return ci.loadIcon(pm);
    }
    
    /**
     * Return the icon resource identifier to use for this match.  If the
     * match defines an icon, that is used; else if the activity defines
     * an icon, that is used; else, the application icon is used.
     * 
     * @return The icon associated with this match.
     */
    public final int getIconResource() {
        if (icon != 0) return icon;
        final ComponentInfo ci = getComponentInfo();
        if (ci != null) return ci.getIconResource();
        return 0;
    }


    public void dump(Printer pw, String prefix) {
        if (filter != null) {
            pw.println(prefix + "Filter:");
            filter.dump(pw, prefix + "  ");
        }
        pw.println(prefix + "priority=" + priority
                + " preferredOrder=" + preferredOrder
                + " match=0x" + Integer.toHexString(match)
                + " specificIndex=" + specificIndex
                + " isDefault=" + isDefault);
        if (resolvePackageName != null) {
            pw.println(prefix + "resolvePackageName=" + resolvePackageName);
        }
        if (labelRes != 0 || nonLocalizedLabel != null || icon != 0) {
            pw.println(prefix + "labelRes=0x" + Integer.toHexString(labelRes)
                    + " nonLocalizedLabel=" + nonLocalizedLabel
                    + " icon=0x" + Integer.toHexString(icon));
        }
        if (activityInfo != null) {
            pw.println(prefix + "ActivityInfo:");
            activityInfo.dump(pw, prefix + "  ");
        } else if (serviceInfo != null) {
            pw.println(prefix + "ServiceInfo:");
            serviceInfo.dump(pw, prefix + "  ");
        } else if (providerInfo != null) {
            pw.println(prefix + "ProviderInfo:");
            providerInfo.dump(pw, prefix + "  ");
        }
    }
    
    public ResolveInfo() {
    }


    public ResolveInfo(ResolveInfo orig) {
        activityInfo = orig.activityInfo;
        serviceInfo = orig.serviceInfo;
        providerInfo = orig.providerInfo;
        filter = orig.filter;
        priority = orig.priority;
        preferredOrder = orig.preferredOrder;
        match = orig.match;
        specificIndex = orig.specificIndex;
        labelRes = orig.labelRes;
        nonLocalizedLabel = orig.nonLocalizedLabel;
        icon = orig.icon;
        resolvePackageName = orig.resolvePackageName;
        system = orig.system;
    }


    public String toString() {
        final ComponentInfo ci = getComponentInfo();
        StringBuilder sb = new StringBuilder(128);
        sb.append("ResolveInfo{");
        sb.append(Integer.toHexString(System.identityHashCode(this)));
        sb.append(' ');
        ComponentName.appendShortString(sb, ci.packageName, ci.name);
        if (priority != 0) {
            sb.append(" p=");
            sb.append(priority);
        }
        if (preferredOrder != 0) {
            sb.append(" o=");
            sb.append(preferredOrder);
        }
        sb.append(" m=0x");
        sb.append(Integer.toHexString(match));
        sb.append('}');
        return sb.toString();
    }


    public int describeContents() {
        return 0;
    }


    public void writeToParcel(Parcel dest, int parcelableFlags) {
        if (activityInfo != null) {
            dest.writeInt(1);
            activityInfo.writeToParcel(dest, parcelableFlags);
        } else if (serviceInfo != null) {
            dest.writeInt(2);
            serviceInfo.writeToParcel(dest, parcelableFlags);
        } else if (providerInfo != null) {
            dest.writeInt(3);
            providerInfo.writeToParcel(dest, parcelableFlags);
        } else {
            dest.writeInt(0);
        }
        if (filter != null) {
            dest.writeInt(1);
            filter.writeToParcel(dest, parcelableFlags);
        } else {
            dest.writeInt(0);
        }
        dest.writeInt(priority);
        dest.writeInt(preferredOrder);
        dest.writeInt(match);
        dest.writeInt(specificIndex);
        dest.writeInt(labelRes);
        TextUtils.writeToParcel(nonLocalizedLabel, dest, parcelableFlags);
        dest.writeInt(icon);
        dest.writeString(resolvePackageName);
        dest.writeInt(system ? 1 : 0);
    }


    public static final Creator<ResolveInfo> CREATOR
            = new Creator<ResolveInfo>() {
        public ResolveInfo createFromParcel(Parcel source) {
            return new ResolveInfo(source);
        }
        public ResolveInfo[] newArray(int size) {
            return new ResolveInfo[size];
        }
    };


    private ResolveInfo(Parcel source) {
        activityInfo = null;
        serviceInfo = null;
        providerInfo = null;
        switch (source.readInt()) {
            case 1:
                activityInfo = ActivityInfo.CREATOR.createFromParcel(source);
                break;
            case 2:
                serviceInfo = ServiceInfo.CREATOR.createFromParcel(source);
                break;
            case 3:
                providerInfo = ProviderInfo.CREATOR.createFromParcel(source);
                break;
            default:
                Slog.w(TAG, "Missing ComponentInfo!");
                break;
        }
        if (source.readInt() != 0) {
            filter = IntentFilter.CREATOR.createFromParcel(source);
        }
        priority = source.readInt();
        preferredOrder = source.readInt();
        match = source.readInt();
        specificIndex = source.readInt();
        labelRes = source.readInt();
        nonLocalizedLabel
                = TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(source);
        icon = source.readInt();
        resolvePackageName = source.readString();
        system = source.readInt() != 0;
    }
    
    public static class DisplayNameComparator
            implements Comparator<ResolveInfo> {
        public DisplayNameComparator(PackageManager pm) {
            mPM = pm;
            mCollator.setStrength(Collator.PRIMARY);
        }


        public final int compare(ResolveInfo a, ResolveInfo b) {
            CharSequence  sa = a.loadLabel(mPM);
            if (sa == null) sa = a.activityInfo.name;
            CharSequence  sb = b.loadLabel(mPM);
            if (sb == null) sb = b.activityInfo.name;
            
            return mCollator.compare(sa.toString(), sb.toString());
        }


        private final Collator   mCollator = Collator.getInstance();
        private PackageManager   mPM;
    }
}
0
阅读全文
0 0
原创粉丝点击