DBILITY

android downloded apk file version check and install 본문

android/java

android downloded apk file version check and install

DBILITY 2024. 5. 9. 12:16
반응형

res/xml/path.xml

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path
        name="external_files"
        path="." />
</paths>

AndroidManifest.xml

<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
......
<provider
    android:name="androidx.core.content.FileProvider"
    android:authorities="${applicationId}.provider"
    android:exported="false"
    android:grantUriPermissions="true">
    <meta-data
        android:name="android.support.FILE_PROVIDER_PATHS"
        android:resource="@xml/path" />
</provider>
//출처를 알 수 없는 앱 설치 권한
if (!getPackageManager().canRequestPackageInstalls()) {
    Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES);
    intent.setData(Uri.parse(String.format("package:%s", getPackageName())));
    if (intent.resolveActivity(getPackageManager()) != null) {        
        startActivity(intent);
    }
}

//build.gradle
buildConfigField("String", "APP_DOWN_FULL_PATH", '"http://........../app-debug.apk"')
//java code
private String apkFile = BuildConfig.APP_DOWN_FULL_PATH.substring(BuildConfig.APP_DOWN_FULL_PATH.lastIndexOf("/") + 1);
private String outputFilePath = this.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS.concat("/app/").concat(apkFile)).toString();

File file = new File(outputFilePath);
Uri apkUri = FileProvider.getUriForFile(LoginActivity.this, BuildConfig.APPLICATION_ID + ".provider", file);
                            
PackageInfo packageInfo = getPackageManager().getPackageArchiveInfo(outputFilePath, 0);

String downloadVersion = (packageInfo.versionName + "" + packageInfo.getLongVersionCode()).replace(".", "");
String currentVersion = BuildConfig.VERSION_NAME.replace(".", "").concat(String.valueOf(BuildConfig.VERSION_CODE));

if (downloadVersion.compareTo(currentVersion) > 0) {
    if (DEBUG) {
        Log.e(TAG, "UPDATE");
    }
    Intent intent = new Intent(Intent.ACTION_VIEW);
    //intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
    intent.setData(apkUri);
    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
    intent.putExtra(Intent.EXTRA_NOT_UNKNOWN_SOURCE, true);
    startActivity(intent);
    finish();
}

 

반응형
Comments