AndroidManifest.xml

 

[필요 퍼미션]

<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

 

 

<provider
     android:name="androidx.core.content.FileProvider"
     android:authorities="kr.xxxx.xxxxxxxx.fileprovider"
     android:exported="false"
     android:grantUriPermissions="true">
     <meta-data
         android:name="android.support.FILE_PROVIDER_PATHS"
         android:resource="@xml/xxxx_provider" />
</provider>

 

[xxxx_provider.xml]

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

 

 

public void convertBase64StringToFileAndStoreIt(String base64, String fileMimeType, String fileName) throws IOException {
        /**
         * 노티피케이션 퍼미션 여부 확인
         */
        if (CommonUtil.notificationPermissionCheck(getContext(), "알림설정", "푸쉬 알림이 차단되어있습니다.\r\n알림 설정해주세요.") == false) {
            return;
        }

        final int notificationId = 1;

        MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
		
        String extension = "";
        if (fileMimeType.length() == 0) {	// MimeType이 없을 경우
            int beginIndex = base64.indexOf(":");
            int endIndex = base64.indexOf(";");
            fileMimeType = base64.substring(beginIndex + 1, endIndex);
            extension = mimeTypeMap.getExtensionFromMimeType(fileMimeType);
        } else {
            extension = mimeTypeMap.getExtensionFromMimeType(fileMimeType);
        }

        // 파일생성 (파일명 처리)
        final File dwldsPath;
        if (fileName == null || fileName.length() <= 0) { // 파일명이 없을경우
            String currentDateTime = DateFormat.getDateTimeInstance().format(new Date());
            String newTime = currentDateTime.replaceFirst(", ","_").replaceAll(" ","_").replaceAll(":","-");
            fileName = newTime + "." + extension;
            dwldsPath = new File(Environment.getExternalStoragePublicDirectory(
                    Environment.DIRECTORY_DOWNLOADS) + "/" + fileName);
        } else {
            dwldsPath = new File(Environment.getExternalStoragePublicDirectory(
                    Environment.DIRECTORY_DOWNLOADS) + "/" + fileName);
        }
        // 파일 데이터 추출
        String regex = base64.split("\\,")[1];
        byte[] fileAsBytes = Base64.decode(regex, 0);

        // 파일 데이터 저장
        try {
            FileOutputStream os = new FileOutputStream(dwldsPath);
            os.write(fileAsBytes);
            os.flush();
            os.close();
        } catch (Exception e) {
            Toast.makeText(getContext(), "FAILED TO DOWNLOAD THE FILE!", Toast.LENGTH_SHORT).show();
            Log.e("FileOutputStreak Exception", e.getMessage());
        }

        // 다운로드 알림 푸쉬 전송 
        if (dwldsPath.exists()) {

            Intent intent = new Intent();
            intent.setAction(android.content.Intent.ACTION_VIEW);

            //Provider xml 파일 필요 (Manifest.xml 추가)
            Uri apkURI = FileProvider.getUriForFile(getContext(),getContext().getPackageName() + ".fileprovider", dwldsPath);
            intent.setDataAndType(apkURI, MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension));
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

            PendingIntent pendingIntent;

            if (Build.VERSION.SDK_INT >= 31) {
                if (Build.VERSION.SDK_INT >= 34) {
                    pendingIntent = PendingIntent.getActivity(getContext(), 0, intent, PendingIntent.FLAG_IMMUTABLE);
                } else {
                    pendingIntent = PendingIntent.getActivity(getContext(), 0, intent, PendingIntent.FLAG_IMMUTABLE);
                }
            } else {
                pendingIntent = PendingIntent.getActivity(getContext(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
            }

            String NOTIFICATION_CHANNEL_ID = "DEFAULT";
            final NotificationManager notificationManager = (NotificationManager) getContext().getSystemService(NOTIFICATION_SERVICE);
            NotificationCompat.Builder builder = new NotificationCompat.Builder(getContext(), NOTIFICATION_CHANNEL_ID)
                    .setContentTitle("타이틀명")
                    .setContentText(fileName + " 파일다운로드 완료.")
                    .setSmallIcon(android.R.drawable.stat_sys_download_done)
                    .setPriority(NotificationCompat.PRIORITY_HIGH)
                    .setContentIntent(pendingIntent)
                    .setWhen(System.currentTimeMillis())
                    .setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE)
                    .setAutoCancel(true);


            if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { // >= 26
                CharSequence channelName = getContext().getPackageName();//"노티피케이션 채널";
                String description = "해당 채널에 대한 설명";
                int importance = NotificationManager.IMPORTANCE_HIGH;

                NotificationChannel notificationChannel = new NotificationChannel(
                        NOTIFICATION_CHANNEL_ID,
                        channelName,
                        importance
                );
                notificationChannel.setDescription(description);

                if (notificationManager != null) {
                    notificationManager.createNotificationChannel(notificationChannel);

                }
            }

            notificationManager.notify(notificationId, builder.build());
        }
        Toast.makeText(getContext(), "FILE DOWNLOADED!", Toast.LENGTH_SHORT).show();
    }

+ Recent posts