LoginSignup
0
0

Android端末内、Downloadフォルダ内にある特定のファイル(.apk)削除。

Posted at

■用途

・apkのバージョンアップにともなうダウンロードで「Toyama_Touhoku_Tana_App (1).apk」
「Toyama_Touhoku_Tana_App (2).apk」
「Toyama_Touhoku_Tana_App (3).apk」
などにならないように、

APKをダウンロードして、アプリをインストールして起動した瞬間に、ダウンロードフォルダ内の対象のAPKファイルを削除する。

■ イメージ画像

ファイル名 ファイル名

■ ソースコード

java MainActivity.java
 protected void onCreate(Bundle savedInstanceState) {
     
    // === onCreate 内

/**
         *  ================== パーミッションリクエスト ====================
         */
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            if (Environment.isExternalStorageManager()) {
                // アクセス許可がすでに与えられている場合の処理
                System.out.println("========== パーミッション 許可済み ===========");

                /**
                 *  削除 function
                 */
                String fileName = "Toyama_Touhoku_Tana_App.apk";
                // パーミッションが許可されている場合はファイルを削除
                deleteFileFromDownloads(this, fileName);

                String fileName_02 = "Toyama_Touhoku_Tana_App (1).apk";
                // パーミッションが許可されている場合はファイルを削除
                deleteFileFromDownloads(this, fileName_02);

                deleteFile();

            } else {
                System.out.println("========== パーミッション 許可を取る~ ===========");
                Intent intent = new Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION);
                Uri uri = Uri.fromParts("package", getPackageName(), null);
                intent.setData(uri);
                startActivityForResult(intent, REQUEST_CODE);
            }
        } else {

            /**
             *  Android 9以下の処理
             */

            System.out.println("========== ビルドバージョン変えて~ ===========");

            requestWriteExternalStoragePermission();
        }


} // ========================= END onCreate

  @Override
    protected void onResume() {
        super.onResume();
        // バックグラウンドからの復帰時の処理

        /**
         *  APK 削除処理
         */
        String fileName = "Toyama_Touhoku_Tana_App.apk";
        // パーミッションが許可されている場合はファイルを削除
        deleteFileFromDownloads(this, fileName);

        String fileName_02 = "Toyama_Touhoku_Tana_App (1).apk";
        // パーミッションが許可されている場合はファイルを削除
        deleteFileFromDownloads(this, fileName_02);

        // === deleteFile 関数実行
        deleteFile();

        /**
         * APK android 9以下 削除処理
         */
        requestWriteExternalStoragePermission();
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        // バックグラウンドからの復帰時の処理
        user_input.setText("");
        user_view.setText("");

        /**
         *  APK 削除処理
         */
        String fileName = "Toyama_Touhoku_Tana_App.apk";
        // パーミッションが許可されている場合はファイルを削除
        deleteFileFromDownloads(this, fileName);

        String fileName_02 = "Toyama_Touhoku_Tana_App (1).apk";
        // パーミッションが許可されている場合はファイルを削除
        deleteFileFromDownloads(this, fileName_02);

        // === deleteFile 関数実行
        deleteFile();

        /**
         * APK android 9以下 削除処理
         */
        requestWriteExternalStoragePermission();
    }

 /**
     *  ファイル削除 media api
     */
    private void deleteFileFromDownloads(Context context, String fileName) {
        ContentResolver contentResolver = context.getContentResolver();
        Uri downloadsUri = null;

        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.Q) {
            downloadsUri = MediaStore.Downloads.EXTERNAL_CONTENT_URI;
        }

        System.out.println("========== downloadsUri:::===========" + downloadsUri);

        int deletedRows = 0;
        try {

            String selection = MediaStore.Downloads.DISPLAY_NAME + "=?";
            String[] selectionArgs = new String[]{fileName};

            deletedRows = contentResolver.delete(downloadsUri, selection, selectionArgs);

        } catch (NullPointerException e) {
            e.printStackTrace();
        }

        if (deletedRows > 0) {
            Log.d(TAG, "============== 削除 OK ===============");
        } else {
            Log.d(TAG, "============== 削除 NG もうちょいよ~ ===============");
        }
    }


 // パーミッションのリクエスト
    private void requestWriteExternalStoragePermission() {
        // パーミッションが既に許可されているかチェック
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            // パーミッションをリクエスト
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_PERMISSION_WRITE_EXTERNAL_STORAGE);
        } else {
            // パーミッションがすでに許可されている場合はファイルの削除処理を実行
            deleteFileFromDownloadDirectory();
        }
    }


 // ダウンロードディレクトリ内のファイルを削除する処理
    private void deleteFileFromDownloadDirectory() {

        String downloadFolderPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath();
        File downloadFolder = new File(downloadFolderPath);


        /**
         *  === 削除処理 === Files.delete(path);
         */

        String fileName = "";


            File[] files = downloadFolder.listFiles();

            for (File file : files){
                fileName = file.getName(); // ファイル名取得
                System.out.println("fileName for:::" + fileName);

                if(fileName.equals("Toyama_Touhoku_Tana_App.apk")) {

                    System.out.println(" =========== Files.delete(path) 削除処理 開始 ===========");

                    // === ファイル削除
                    file.delete();
                    System.out.println(" Android 9 以下 ファイル削除 成功 ::: ファイルが削除されました。");

                }  else if(fileName.equals("Toyama_Touhoku_Tana_App (1).apk")) {

                    System.out.println(" =========== Files.delete(path) 削除処理 開始 ===========");
                    // === ファイル削除
                    file.delete();
                    System.out.println("Android 9 以下 ファイル削除 成功 ::: ファイルが削除されました。");

                }

                String filepaht = file.getPath(); // パス取得

                System.out.println("Android 9 以下 fileName:::" + fileName);
                System.out.println("Android 9 以下 filepaht:::" + filepaht);
            }



    } // === deleteFileFromDownloadDirectory END


 /**
     *  内部ストレージ ダウンロードフォルダ 内 ファイル削除
     */
    private void deleteFile() {

        // === 使用
        String downloadFolderPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath();
        File downloadFolder = new File(downloadFolderPath);
        File[] files = downloadFolder.listFiles();

        for (File file : files){
            String fileName = file.getName(); // ファイル名取得
            String filepaht = file.getPath(); // パス取得

            System.out.println("fileName:::" + fileName);
            System.out.println("filepaht:::" + filepaht);
        }

        // 内部ストレージパス
        String filePath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + File.separator + "Toyama_Touhoku_Tana_App.apk";

        String downloadDir_tmp = context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath() + File.separator + "Toyama_Touhoku_Tana_App.apk";
        System.out.println("downloadDir_tmp:::" + downloadDir_tmp);

        String downloadDir_001 = File.separator + "ome_2021-1.jpeg";
        System.out.println("downloadDir_001:::" + downloadDir_001);

        // 外部ストレージパス
       // String filePath = getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS) + File.separator + "Toyama_Touhoku_Tana_App.apk";
        System.out.println("filePath:::" + filePath);

        String fileName = "";

        /**
         *  === 削除処理 === Files.delete(path);
         */
        try {

            File[] filess = downloadFolder.listFiles();

            for (File file : filess){
                fileName = file.getName(); // ファイル名取得
                System.out.println("fileName for:::" + fileName);

                if(fileName.equals("tanaoroshi.apk")) {

                    System.out.println(" =========== Files.delete(path) 削除処理 開始 ===========");

                    Path path = null;
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                        path = Paths.get(file.getPath());
                    }
                    System.out.println("file.getPath():::" + file.getPath());

                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                        Files.delete(path);
                    }
                    System.out.println(" Files.delete(path) ::: ファイルが削除されました。");

                }  else if(fileName.equals("Toyama_Touhoku_Tana_App (1).apk")) {

                    System.out.println(" =========== Files.delete(path) 削除処理 開始 ===========");

                    Path path = null;
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                        path = Paths.get(file.getPath());
                    }
                    System.out.println("file.getPath():::" + file.getPath());

                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                        Files.delete(path);
                    }
                    System.out.println(" Files.delete(path) ::: ファイルが削除されました。");

                }

                String filepaht = file.getPath(); // パス取得

                System.out.println("fileName:::" + fileName);
                System.out.println("filepaht:::" + filepaht);
            }

        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("ファイルの削除中にエラーが発生しました。");
        }

    }
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0