Android: 安装另一个应用程序并检测它何时首次启动

Android: Install another app and detect when it is launched the first time

我有一个可以安装其他应用程序的应用程序,就像 Google Play 商店一样。要完成分析链,我需要能够检测安装的应用程序何时首次启动。

Google Play 商店确实以某种方式实现了它。

Android 系统会为您完成。首次启动已安装的应用程序时,程序包管理器会向安装程序广播 Intent.ACTION_PACKAGE_FIRST_LAUNCH。为确保您收到它,您需要:

  • 安装应用程序后立即设置安装程序包名称,因为广播仅限于为正在启动的应用程序设置的安装程序包名称。

    getPackageManager().setInstallerPackageName("com.example", getApplicationContext().getPackageName());
    
  • 确保您没有使用 PackageManager.INSTALL_REPLACE_EXISTING,因为它会被假定为更新,系统不会为其发送广播

  • 在运行时而不是在清单中注册您的接收器以进行操作Intent.ACTION_PACKAGE_FIRST_LAUNCH

正在注册广播接收器:

registerReceiver(new LaunchReceiver(), new IntentFilter(Intent.ACTION_PACKAGE_FIRST_LAUNCH));

示例广播接收器:

public class LaunchReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getData() != null) {
            Log.d(TAG, "Package name: " + intent.getDataString().replace("package:", ""));
        }
    }
}

有关更多信息,请阅读此处的实际代码:PackageManagerService.notifyFirstLaunch()