본문 바로가기
프로그래밍/Java

[Java] Base64 디코딩해서 apk 파일 실행

by Youngs_ 2024. 8. 30.

아래 코드는 서버에서 Base64를 인코딩해서 주었을때 해당String값을 이용해서 디코딩 하여 apk파일을 실행하는 코드이다.

byte[] decodedBytes = Base64.decode(apkInfo.FileDecode, Base64.DEFAULT);

// 2. 임시 파일 생성 및 저장
File tempFile = File.createTempFile("temp_apk", ".apk", context.getCacheDir());
FileOutputStream outputStream = new FileOutputStream(tempFile);
outputStream.write(decodedBytes);
outputStream.close();

// 3. Download 폴더에 파일 복사
File downloadDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
File apkFile = new File(downloadDir, apkInfo.FileName);

try (FileInputStream in = new FileInputStream(tempFile); FileOutputStream out = new FileOutputStream(apkFile)) {
    byte[] buffer = new byte[1024];
    int length;
    while ((length = in.read(buffer)) > 0) {
        out.write(buffer, 0, length);
    }
}

// 4. 설치 진행
Uri contentUri = FileProvider.getUriForFile(context, "패키지명.provider", apkFile);
Intent installIntent = new Intent(Intent.ACTION_VIEW);
installIntent.setDataAndType(contentUri, "application/vnd.android.package-archive");
installIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_GRANT_READ_URI_PERMISSION);
context.startActivity(installIntent);

// 5. 임시 파일 삭제
boolean deleted = tempFile.delete();
if (deleted) {
    // 파일 삭제 성공
    Log.d("FileDelete", "임시 파일 삭제 성공");
} else {
    // 파일 삭제 실패
    Log.e("FileDelete", "임시 파일 삭제 실패");
}

    

4번의 FileProvider.getUriForFile의 두번째 파라미터는 Manifest.xml의 provider를 선언후 입력해야한다.  

AndroidManifest.xml

<application
>
....
    <provider
        android:name="android.support.v4.content.FileProvider"
        android:authorities="패키지명.provider"
        android:exported="false"
        android:grantUriPermissions="true">
        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/provider_paths" />
    </provider>
<application/>

 

@xml/provider_path

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

댓글