Android Development Notes (177) Install apps with FileProvider

Posted by kurky on Mon, 01 Nov 2021 17:35:44 +0100

In addition to the file provider required to send MMS messages, the FileProvider is also required to install applications. Not only can attached pictures of MMS be queried in the media library, but the APK installation package for the application can also be found in the media library. Finding installation packages still relies on content parsers, which are implemented in a way similar to querying pictures, such as declaring the following object variables beforehand:

private List<ApkInfo> mApkList = new ArrayList<ApkInfo>(); // List of installation packages
private Uri mFilesUri = MediaStore.Files.getContentUri("external"); // Uri of memory card
private String[] mFilesColumn = new String[]{ // Array of field names for the media library
        MediaStore.Files.FileColumns._ID, // number
        MediaStore.Files.FileColumns.TITLE, // Title
        MediaStore.Files.FileColumns.SIZE, // file size
        MediaStore.Files.FileColumns.DATA, // File Path
        MediaStore.Files.FileColumns.MIME_TYPE}; // media type

Another example of loading code is to find a list of installation packages from the content parser to the media library:

// Load installation package list
private void loadApkList() {
    mApkList.clear(); // Empty installation package list
    // Find all apk files on the memory card, where mime_ Typee specifies the file type of the apk, or determines if the file path ends in.apk
    Cursor cursor = getContentResolver().query(mFilesUri, mFilesColumn,
            "mime_type='application/vnd.android.package-archive' or _data like '%.apk'", null, null);
    if (cursor != null) {
        // The following iterates through the result set and adds it one by one to the list of installation packages. For simplicity, select only the top ten files
        for (int i=0; i<10 && cursor.moveToNext(); i++) {
            ApkInfo apk = new ApkInfo(); // Create an installation package information object
            apk.setId(cursor.getLong(0)); // Set installation package number
            apk.setName(cursor.getString(1)); // Set Installation Package Name
            apk.setSize(cursor.getLong(2)); // Set the file size of the installation package
            apk.setPath(cursor.getString(3)); // Set file path for installation package
            mApkList.add(apk); // Add to installation package list
        }
        cursor.close(); // Close database cursor
    }
}

Once an installation package has been found, you usually need to get its package name, version name, version number, and so on. At this time, you can call the getPackageArchiveInfo method of the application package manager to extract the package information from the installation package file. The packageName property value of the package information object is the application package name, the versionName property value is the version name, and the versionCode property value is the version number. Here is an example of code that uses pop-ups to show package information:

// Show the prompt dialog for installing apk
private void showAlert(final ApkInfo apkInfo) {
    PackageManager pm = getPackageManager(); // Get Application Package Manager
    // Get package information for the apk file
    PackageInfo pi = pm.getPackageArchiveInfo(apkInfo.getPath(), PackageManager.GET_ACTIVITIES);
    if (pi != null) { // Package information can be found
        String desc = String.format("Apply package name:%s\n Version name:%s\n Version Code:%s\n File path:%s",
                pi.packageName, pi.versionName, pi.versionCode, apkInfo.getPath());
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Is the application installed?"); // Set the title of the reminder dialog
        builder.setMessage(desc); // Set the message content of the reminder dialog
        builder.setPositiveButton("yes", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                installApk(apkInfo.getPath()); // Install APK for specified path
            }
        });
        builder.setNegativeButton("no", null);
        builder.create().show(); // Show reminder dialog
    } else { // Package information not found
        ToastUtil.show(this, "This installation package is damaged, please choose another one");
    }
}

With the file path of the installation package, you can open the installation program of the system to perform the installation operation, at which point you also need to pass the Uri object of the installation package. The detailed calling code for the application installation is as follows:

// Install APK for specified path
private void installApk(String path) {
    Uri uri = Uri.parse(path); // Create a Uri object from the specified path
    // Compatible with Android 7.0, change the Uri way to access files to FileProvider
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        // Get Uri access to installation package files through FileProvider
        uri = FileProvider.getUriForFile(this,
                BuildConfig.APPLICATION_ID + ".fileProvider", new File(path));
    }
    Intent intent = new Intent(Intent.ACTION_VIEW); // The intent of creating a browsing action
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // Open a new page
    intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); // Read permission required
    // Set Uri's data type to APK file
    intent.setDataAndType(uri, "application/vnd.android.package-archive");
    startActivity(intent); // Start the application installer that comes with the system
}

Note that Android 8.0 requires permission REQUEST_to start installing applications INSTALL_ PACKAGES opens AndroidManifest.xml, supplementing the following permission request configuration:

<!-- Install the application request, Android8.0 Need -->
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />

That's it, compile and run App, and open the test page to automatically load the list of installation packages as shown in the following image.

Click on an installation package and a confirmation dialog box appears as illustrated below.

 

By clicking the Yes button on the confirmation dialog box, you jump to the application installation page shown below, and the rest of the installation is handed over to the system.

 


Click here to see the full catalog of Android Development Notes

Topics: Java Android FileProvider