在判断一个应用程序是系统程序还是用户程序时,经常用到下面一端代码:
int flags = packInfo.applicationInfo.flags;//应用程序信息的标记
if((flags&ApplicationInfo.FLAG_SYSTEM)==0){
//用户程序
appInfo.setUserApp(true);
}else{
//系统程序
appInfo.setUserApp(false);
}
为何获得应用程序的标记后,后面要用flags&ApplicationInfo.FLAG_SYSTEM的方式来判断是否为系统程序呢?
点进packInfo.applicationInfo.flags的源码:
......
public static final int FLAG_SYSTEM = 1<<0;
/**
* Value for {@link #flags}: set to true if this application would like to
* allow debugging of its
* code, even when installed on a non-development system. Comes
* from {@link android.R.styleable#AndroidManifestApplication_debuggable
* android:debuggable} of the <application> tag.
*/
public static final int FLAG_DEBUGGABLE = 1<<1;
/**
* Value for {@link #flags}: set to true if this application has code
* associated with it. Comes
* from {@link android.R.styleable#AndroidManifestApplication_hasCode
* android:hasCode} of the <application> tag.
*/
public static final int FLAG_HAS_CODE = 1<<2;
/**
* Value for {@link #flags}: set to true if this application is persistent.
* Comes from {@link android.R.styleable#AndroidManifestApplication_persistent
* android:persistent} of the <application> tag.
*/
public static final int FLAG_PERSISTENT = 1<<3;
/**
* Value for {@link #flags}: set to true if this application holds the
* {@link android.Manifest.permission#FACTORY_TEST} permission and the
* device is running in factory test mode.
*/
public static final int FLAG_FACTORY_TEST = 1<<4;
......
可以看到每个标记都是1<<序号的形式,即表示1向左位移动n位,即:
1<<0=1;左移0位
1<<1=2;左移1位
1<<2=4;左移2位
1<<3=8;左移3位
……
为什么google要用这种方式设计呢?我们来看,上面几个标记位移后8位二进制数为:
标记 | 值 |
---|---|
FLAG_SYSTEM | 0000 0001 |
FLAG_DEBUGGABLE | 0000 0010 |
FLAG_HAS_CODE | 0000 0100 |
FLAG_PERSISTENT | 0000 1000 |
而获得int flags = packInfo.applicationInfo.flags;//应用程序信息的标记
后,拿flag与之相与,我们知道与操作,对应二进制位上全为1才为1。
假设flag=0011,与上面系统标记相与,结果中:FLAG_DEBUGGABLE和FLAG_SYSTEM不为0,表示这个程序既有FLAG_DEBUGGABLE和FLAG_SYSTEM两个属性。
所以,这种设计的方便之处在于,方便比较和一个flag能表示很多个状态。