【Android】判断某个AP是否在系统中存在(PackageManager与PackageInfo)

本文介绍如何使用Android SDK中的PackageManager类和PackageInfo类来判断特定应用是否已安装在系统中,并提供了一个实用的工具类实现。通过解析应用的Manifest.xml文件,可以获取到应用的详细信息,包括权限、服务、接收者等。实现了一个方法isAppInstalled,通过传入上下文和应用包名参数,判断应用是否已安装。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

【0】我们可以使用getPackageManager() 方法来查询安装在系统上的AP.

public abstract class

PackageManager

extends Object
java.lang.Object
android.content.pm.PackageManager
Known Direct Subclasses
Class for retrieving various kinds of information related to the application packages that are currently installed on the device. You can find this class throughgetPackageManager().
【1】使用从Manifest.xml文件中获得到的PackageInfo来取得AP的信息.
public class

PackageInfo

extends Object
implements Parcelable
java.lang.Object
android.content.pm.PackageInfo

Overall information about the contents of a package. This corresponds to all of the information collected from AndroidManifest.xml.

public static finalCreator<PackageInfo>CREATOR
Since: API Level 1

publicActivityInfo[]activities
Since: API Level 1

Array of all<activity>tags included under <application>, or null if there were none. This is only filled in if the flagGET_ACTIVITIESwas set.

publicApplicationInfoapplicationInfo
Since: API Level 1

Information collected from the <application> tag, or null if there was none.

publicConfigurationInfo[]configPreferences
Since: API Level 3

Application specified preferred configuration<uses-configuration>tags included under <manifest>, or null if there were none. This is only filled in if the flagGET_CONFIGURATIONSwas set.

public longfirstInstallTime
Since: API Level 9

The time at which the app was first installed. Units are as percurrentTimeMillis().

public int[]gids
Since: API Level 1

All kernel group-IDs that have been assigned to this package. This is only filled in if the flagGET_GIDSwas set.

publicInstrumentationInfo[]instrumentation
Since: API Level 1

Array of all<instrumentation>tags included under <manifest>, or null if there were none. This is only filled in if the flagGET_INSTRUMENTATIONwas set.

public longlastUpdateTime
Since: API Level 9

The time at which the app was last updated. Units are as percurrentTimeMillis().

publicStringpackageName
Since: API Level 1

The name of this package. From the <manifest> tag's "name" attribute.

publicPermissionInfo[]permissions
Since: API Level 1

Array of all<permission>tags included under <manifest>, or null if there were none. This is only filled in if the flagGET_PERMISSIONSwas set.

publicProviderInfo[]providers
Since: API Level 1

Array of all<provider>tags included under <application>, or null if there were none. This is only filled in if the flagGET_PROVIDERSwas set.

publicActivityInfo[]receivers
Since: API Level 1

Array of all<receiver>tags included under <application>, or null if there were none. This is only filled in if the flagGET_RECEIVERSwas set.

publicFeatureInfo[]reqFeatures
Since: API Level 5

The features that this application has said it requires.

publicString[]requestedPermissions
Since: API Level 1

Array of all<uses-permission>tags included under <manifest>, or null if there were none. This is only filled in if the flagGET_PERMISSIONSwas set. This list includes all permissions requested, even those that were not granted or known by the system at install time.

publicServiceInfo[]services
Since: API Level 1

Array of all<service>tags included under <application>, or null if there were none. This is only filled in if the flagGET_SERVICESwas set.

publicStringsharedUserId
Since: API Level 3

The shared user ID name of this package, as specified by the <manifest> tag'ssharedUserIdattribute.

public intsharedUserLabel
Since: API Level 3

The shared user ID label of this package, as specified by the <manifest> tag'ssharedUserLabelattribute.

publicSignature[]signatures
Since: API Level 1

Array of all signatures read from the package file. This is only filled in if the flagGET_SIGNATURESwas set.

public intversionCode
Since: API Level 1

The version number of this package, as specified by the <manifest> tag'sversionCodeattribute.

publicStringversionName
Since: API Level 1

The version name of this package, as specified by the <manifest> tag'sversionNameattribute.

【2】使用上面两个类来实现一个判断某个AP是否安装在系统中的工具类
	/**
	 * Whether the AP was installed
	 * @param context:the Context
	 * @param packageName:the ap packageName
	 * @return
	 */
	public static boolean isAppInstalled(Context context, String packageName)
	{
		//获取到一个PackageManager的instance
		final PackageManager packageManager = context.getPackageManager();
		//PERMISSION_GRANTED = 0
		List<PackageInfo> mPackageInfo = packageManager.getInstalledPackages(0);
		boolean flag = false;
		if(mPackageInfo != null)
		{
			String tempName = null;
			for(int i = 0; i < mPackageInfo.size(); i++)
			{
				//获取到AP包名
				tempName = mPackageInfo.get(i).packageName;
				if(tempName != null && tempName.equals(packageName))
				{
					MyLogger.kLog().i("Package[" + packageName + "]:is installed.");
					flag = true;
					break;
				}
			}
		}
		return flag;
	}


 
 
 
public abstractList<PackageInfo>getInstalledPackages(int flags)
Since: API Level 1

Return a List of all packages that are installed on the device.

Parameters
flags Additional option flags. Use any combination ofGET_ACTIVITIES,GET_GIDS,GET_CONFIGURATIONS,GET_INSTRUMENTATION,GET_PERMISSIONS,GET_PROVIDERS,GET_RECEIVERS,GET_SERVICES,GET_SIGNATURES,GET_UNINSTALLED_PACKAGESto modify the data returned.
Returns
  • A List of PackageInfo objects, one for each package that is installed on the device. In the unlikely case of there being no installed packages, an empty list is returned. If flag GET_UNINSTALLED_PACKAGES is set, a list of all applications including those deleted with DONT_DELETE_DATA (partially installed apps with data directory) will be returned.


谢谢!

### Kakaogames SDK 接入指南 #### 1. 安装环境 - **IDE**: Android Studio - **JDK**: JDK 8 或更高版本 - **Android SDK**: Android 14 (API 34) - **操作系统**: Android 6.0 (API 23) 或更高版本 - **Gradle 版本**: 6.1.1 #### 2. SDK 环境设置 ##### 2.1. `build.gradle` (项目级别) ```groovy buildscript { repositories { google() mavenCentral() } dependencies { classpath 'com.android.tools.build:gradle:4.0.1' classpath 'com.google.gms:google-services:4.3.3' } } allprojects { repositories { google() mavenCentral() maven { url 'https://devrepo.kakao.com/nexus/content/groups/public/' name 'kakao' } maven { url 'https://s3.ap-northeast-2.amazonaws.com/kakao-sdk-release/release/' name 'Kakaogames' } } } ``` ##### 2.2. `gradle.properties` ```properties org.gradle.jvmargs=-Xmx4608M KAKAO_GAME_SDK_VERSION=4.0.0 android.useAndroidX=true android.enableJetifier=true ``` ##### 2.3. `build.gradle` (应用级别) ```groovy apply plugin: 'com.android.application' android { compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 } } dependencies { implementation "com.kakaogame.publishing:idp_device:$KAKAO_GAME_SDK_VERSION" implementation "com.kakaogame.publishing:idp_kakao:$KAKAO_GAME_SDK_VERSION" implementation "com.kakaogame.publishing:idp_siwa:$KAKAO_GAME_SDK_VERSION" implementation "com.kakaogame.publishing:gamesdk:$KAKAO_GAME_SDK_VERSION" } apply plugin: 'com.google.gms.google-services' ``` ##### 2.4. 外部库依赖 必要库及其版本如下表所示。这些库在连接到 Kakaogames SDK 时会自动包含。 | SDK 版本 | 模块 | 外部库 | | -- | --- | | 4.0.1 | gamesdk | com.google.android.gms:play-services-ads-identifier:18.0.0<br>androidx.appcompat:appcompat:1.3.1<br>androidx.legacy:legacy-support-v4:1.0.0<br>androidx.core:core-ktx:1.6.0<br>org.jetbrains.kotlin:kotlin-stdlib-jdk7:1.5.31<br>org.jetbrains.kotlinx:kotlinx-coroutines-core:1.1.0<br>org.jetbrains.kotlinx:kotlinx-coroutines-android:1.1.0<br>androidx.databinding:viewbinding:7.0.4<br>com.google.android.play:review:2.0.0<br>com.google.android.play:app-update:2.0.0<br>com.android.installreferrer:installreferrer:2.2<br>com.github.bumptech.glide:glide:4.10.0<br>androidx.cardview:cardview:1.0.0 | | 4.0.1 | idp_kakao | com.kakao.sdk:{module}:2.13.0 | | 4.0.1 | idp_facebook | com.facebook.android:facebook-android-sdk:14.1.1 | | 4.0.1 | idp_googlegame | com.google.android.gms:play-services-auth:20.6.0<br>com.google.android.gms:play-services-games-v2:17.0.0<br>androidx.annotation:annotation:1.0.0 | | 4.0.1 | security | com.google.android.material:material:1.6.1 | | 4.0.1 | payment | com.android.billingclient:billing:6.0.1<br>androidx.recyclerview:recyclerview:1.0.0 | | 4.4.0 | gamesdk | com.google.android.gms:play-services-ads-identifier:18.0.0<br>androidx.appcompat:appcompat:1.6.1<br>androidx.legacy:legacy-support-v4:1.0.0<br>androidx.core:core-ktx:1.10.0<br>org.jetbrains.kotlin:kotlin-stdlib-jdk8:1.8.10<br>org.jetbrains.kotlinx:kotlinx-coroutines-core:1.1.0<br>org.jetbrains.kotlinx:kotlinx-coroutines-android:1.1.0<br>androidx.databinding:viewbinding:7.0.4<br>com.google.android.play:review:2.0.0<br>com.google.android.play:review-ktx:2.0.0<br>com.google.android.play:app-update:2.0.0<br>com.google.android.play:app-update-ktx:2.0.0<br>com.android.installreferrer:installreferrer:2.2<br>com.github.bumptech.glide:glide:4.10.0<br>androidx.cardview:cardview:1.0.0 | | 4.4.0 | idp_kakao | com.kakao.sdk:{module}:2.18.0 | | 4.4.0 | idp_facebook | com.facebook.android:facebook-android-sdk:14.1.1 | | 4.4.0 | idp_googlegame | com.google.android.gms:play-services-auth:20.6.0<br>com.google.android.gms:play-services-games-v2:17.0.0<br>androidx.annotation:annotation:1.0.0 | | 4.4.0 | security | com.google.android.material:material:1.6.1 | | 4.4.0 | payment | com.android.billingclient:billing:6.0.1<br>androidx.recyclerview:recyclerview:1.0.0 | | 4.4.0 | firebase | com.google.firebase:firebase-bom:32.8.1<br>com.google.firebase:firebase-analytics<br>com.google.firebase:firebase-perf<br>com.google.firebase:firebase-crashlytics<br>com.google.firebase:firebase-messaging | 如果游戏使用的外部库上述库有冲突,可以删除冲突的链接,并使用较高版本的库。 #### 3. IDP 身份验证信息设置 ##### 3.1. Kakao 身份验证信息设置 在 `src/main/res/values/kakao_game_kakao_auth.xml` 中添加以下资源文件并设置值。 ```xml <resources> <string name="kakao_app_key">YOUR_KAKAO_APP_KEY</string> </resources> ``` ##### 3.2. SigninWithApple 身份验证信息设置 在 `src/main/res/values/kakao_game_siwa_auth.xml` 中添加以下资源文件并设置值。 ```xml <resources> <string name="siwa_client_id">YOUR_SIWA_CLIENT_ID</string> </resources> ``` #### 4. `AndroidManifest.xml` 文件配置 ##### 4.1. 常规设置 - 设置最小支持的 SDK 版本为 23 或更高:`android:minSdkVersion="23"` - 设置目标 SDK 版本为 31:`android:targetSdkVersion="31"` - 显式声明 `android:exported` - 添加以下权限: - `android.permission.INTERNET` - `android.permission.ACCESS_NETWORK_STATE` - 添加多屏幕处理设置: - `android:resizeableActivity="true"` - 在每个添加的 Activity 中添加以下配置: - `android:configChanges="orientation|screenSize|keyboard|screenLayout|screenSize|smallestScreenSize"` - 对于 API 23 及以上版本,可以指定应用是否使用明文网络流量: - `android:usesCleartextTraffic="true"` - 添加 URL Scheme: - 主 Activity 的 `intent-filter` 设置中,scheme 由 "kakaogame" + 应用 ID 组成(例如,应用 ID 为 123456,则 scheme 值为 "kakaogame123456") ##### 4.2. Kakao 身份验证配置 - 主 Activity 必须包含以下 `intent-filter` 声明: - 声明 `AuthCodeHandlerActivity` 并添加其 `intent-filter` - 对于 Android 12,必须显式声明 `exported` 属性 ##### 4.3. HTTP 使用配置 - 如果 `targetSdkVersion` 设置为 28 或更高版本且游戏使用 HTTP 通信,需要进行以下配置: - 创建 `res/xml/network_security_config.xml` 文件并添加需要 HTTP 通信的域 - 在 `AndroidManifest.xml` 的 `Application` 部分设置 `networkSecurityConfig` ##### 4.4. 游戏支持的语言资源 - 如果库中有游戏不支持的额外语言包,可以删除相应的文件夹(例如,删除日语设置,删除 `KakaoGameSDK > res > values-ja` 文件夹) #### 5. 密钥哈希验证和注册方法 - 构建应用时,需要注册构建机器的密钥哈希。 - 获取调试密钥哈希和发布密钥哈希,并在 [Game Center > Game Management > Key Hash Registration] 菜单中注册。 ##### 5.1. 获取调试密钥哈希 - 开发证书存储在 `debug.keystore` 文件中,别名为 `androiddebugkey`。 - 使用以下命令获取密钥哈希(需在构建样本的机器上执行): ```sh keytool -keystore [debug_keystore_path] | openssl sha1 -binary | openssl base64 ``` - 建议使用 OpenSSL 1.0.2 或更高版本。 ##### 5.2. 获取发布密钥哈希 - 如果在 Game Center 注册密钥哈希后仍收到 `AUTHORIZATION_FAILED: invalid android_key_hash` 错误,可以通过以下方法验证是否使用了正确的密钥哈希: - 暂时修改 `MainActivity` 类中的 `onCreate()` 方法: ```java @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); try { PackageInfo info = getPackageManager().getPackageInfo(getPackageName(), PackageManager.GET_SIGNATURES); for (Signature signature : info.signatures) { MessageDigest md = MessageDigest.getInstance("SHA"); md.update(signature.toByteArray()); String hash = Base64.encodeToString(md.digest(), Base64.DEFAULT); Log.d("KeyHash", hash); } } catch (PackageManager.NameNotFoundException | NoSuchAlgorithmException e) { e.printStackTrace(); } } ``` - 运行代码并在 Logcat 输出中检查密钥哈希。 #### 6. 构建验证 - 验证项目是否成功构建。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值