如何获取最近安装的应用的名称?

时间:2016-12-26 04:42:36

标签: android

我的代码获取了所有最近安装的应用程序的列表,但问题是,我只想要最新的软件包名称(只有一个)。如何修改我的代码呢?

public void RootInstallAPK1(View view) {
    final PackageManager pm = getPackageManager();
    List<ApplicationInfo> packages = pm
            .getInstalledApplications(PackageManager.GET_META_DATA);

    for (ApplicationInfo packageInfo : packages) {
        String packageName = packageInfo.packageName;
        String appFile = packageInfo.sourceDir;
        long lastModified = new File(appFile).lastModified();
        // Use this to get first time install time
        // long installed =
        // context.getPackageManager().getPackageInfo(packageName,
        // 0).firstInstallTime;
        Log.d(TAG, "Installed package :" + packageName);
        Log.d(TAG, "Source dir : " + appFile);
        Log.d(TAG, "Last Modified Time :" + lastModified);

        Toast toast = Toast.makeText(this, packageName, Toast.LENGTH_SHORT);
        toast.show();
    }
}

1 个答案:

答案 0 :(得分:0)

你已经循环了所有已安装的,并且获得了上次修改日期,这在这里非常简单。

long newestInstall = 0;
ApplicationInfo newestApp;

for (ApplicationInfo packageInfo : packages) {

    String appFile = packageInfo.sourceDir;
    long lastModified = new File(appFile).lastModified();

    // check if this is newer then what we already have
    if ( lastModified > newestInstall ) {

        newestInstall = lastModified;
        newestApp = packageInfo;
    }
}

// print the newest app to the log
Log.d(TAG, "Newest App :" + newestApp.packageName);

这将遍历所有已安装的软件包,并继续为每个比最后一个更新的应用程序更新 newestTime newestApp

循环完成后,您将获得最近安装的应用程序。