簡體   English   中英

1小時后如何自動清除應用程序的緩存

[英]How can I clear cache of my app automatically after 1 hr

我正在研究故事應用程序。 在此應用程序中,我們從服務器下載JSON數據,這些數據應保存在緩存中。 我將數據存儲在緩存中,但是我想在特定時間限制后刪除此緩存。

我在緩存中添加數據的代碼如下:

ObjectOutput out = new ObjectOutputStream(new FileOutputStream(new File(getActivity().getCacheDir(),"")+"cacheFile.srl")); 
String tetsing = jsonObject_one.toString(); 
out.writeObject( tetsing );

當您呼叫服務器,接收回調並將您的實體添加到本地數據庫中時,您可以在當前系統毫秒之內長時間保存共享首選項:

long cacheTime = System.currentTimeMillis();

每次打開需要調用服務器的活動時,在執行請求之前,請在共享首選項中檢查時間:

if(timeInSharedPreference < System.currentTimeMillis() * 1000 * 60 * 60) {
    // do the request
    // update DB
}

嘗試這個

//Repeat the alarm for every 1 hour and attach the receiver to be called   after 1 hr interval
    private void repeatAlarm() {
        Date when = new Date(System.currentTimeMillis());
        try {
            Intent someIntent = new Intent(getApplicationContext(), MyReceiver.class); // intent to be launched
            // note this could be getActivity if you want to launch an activity
            PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, // id, optional
                    someIntent, // intent to launch
                    PendingIntent.FLAG_CANCEL_CURRENT); // PendintIntent flag
            AlarmManager alarms = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
            alarms.setRepeating(AlarmManager.RTC_WAKEUP, when.getTime(), AlarmManager.INTERVAL_HOUR, pendingIntent);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //You need to create your own receiver to be called after particular interval of time
    //TODO: Don't forget to declare it in manifest
    public class MyReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            deleteCache(context);
        }
    }

    public static void deleteCache(Context context) {
        try {
            File dir = context.getCacheDir();
            if (dir != null && dir.isDirectory()) {
                deleteDir(dir);
            }
        } catch (Exception e) {}
    }
    //TODO: Add the "android.permission.CLEAR_APP_CACHE" permission in your manifest
    public static boolean deleteDir(File dir) {
        if (dir != null && dir.isDirectory()) {
            String[] children = dir.list();
            for (int i = 0; i < children.length; i++) {
                boolean success = deleteDir(new File(dir, children[i]));
                if (!success) {
                    return false;
                }
            }
        }

希望這可以幫助!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM