android5.0 手機中,快取檔案不能實時重新整理問題,解決辦法.
阿新 • • 發佈:2019-02-11
public class MtpUtils { private static final String ACTION_MEDIA_SCANNER_SCAN_DIR = "android.intent.action.MEDIA_SCANNER_SCAN_DIR"; private static final Logger logger = LoggerFactory.getLogger(MtpUtils.class); /** * Intent.ACTION_MEDIA_SCANNER_SCAN_FILE:掃描指定檔案 * * @param contextContext * @param filePath 檔案路徑 */ public static void scanFileAsync(Context context, String filePath) { Intent scanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE); scanIntent.setData(Uri.fromFile(new File(filePath))); context.sendBroadcast(scanIntent); } /*** 重新整理MTP,重新整理指定資料夾路徑下的所有檔案(只是根目錄下的檔案) * * @param context Context * @param dir 資料夾路徑 */ public static void scanMtpAsync(Context context, String dir) { File[] files = new File(dir).listFiles(new FileFilter() { @Override public boolean accept(File pathname) { returnpathname.isFile(); } }); logger.error("MtpUtils:指定路徑下檔案:{}", files+""); String[] paths = new String[files.length]; for (int co = 0; co < files.length; co++) { paths[co] = files[co].getAbsolutePath(); logger.error("MtpUtils:{}", paths[co]+""); scanFileAsync(context, paths[co]); } } /** * 重新整理MTP,重新整理整個sdcard目錄下,消耗資源 * * @param context Context */ public static void scanMtpAsync(Context context) { String dir = "/sdcard/"; File[] files = new File(dir).listFiles(); logger.error("MtpUtils:指定路徑下檔案:{}", files+""); String[] paths = new String[files.length]; for (int co = 0; co < files.length; co++) { paths[co] = files[co].getAbsolutePath(); logger.error("MtpUtils:{}", paths[co]); if (new File(paths[co]).isDirectory()) { scanMtpAsync(context, paths[co]); logger.error("MtpUtils:是資料夾:{}", paths[co]+""); } else { logger.error("MtpUtils:是檔案:{}", paths[co]+""); scanFileAsync(context, paths[co]); } }
}
}
用法:
在需要匯出檔案的時候,在匯出的完成後的邏輯後面加上:
MtpUtils.scanMtpAsync(this, "/sdcard/匯出/");//重新整理指定目錄下的所有檔案.
這個時候插上usb線,連線電腦,就不用再在改目錄下面新建一個資料夾來採用強制重新整理的方式來刷新出來檔案了!