简体   繁体   中英

How do I manage app cache programmatically? (Clear it upon exiting the app)

I've just created a WebView app that just basically opens a news website and tried to make it faster by storing some stuff in cache. The problem that came up was that whenever some new articles were added to the actual page, the app would not show them, since it already has the main page, along with some others that were visited, stored in cache. So if, for example, you first opened the app, surfed the web for a couple of minutes, and then opened it after a couple of days, it wouldn't have any new articles, just the ones that came before you first opened the app.

Is there any way I can effectively clear the cache when a user starts/kills the app using some code?

Are there any other solutions to this problem that would not make the app much slower?

You can use the clearCache method. You may call it every time the application load, to may the app clear the cache stored on the previous session. Check out the documentation: https://developer.android.com/reference/android/webkit/WebView.html#clearCache(boolean)

WebView mWebView;
mWebView.clearCache(true);

you pass 'true' as parameters to clear not only the RAM cache:

Clears the resource cache. Note that the cache is per-application, so this will clear the cache for all WebViews used.

Create a service and attach it to application. this service should observe application life.

public class AppController extends Application {

    @Override
    public void onCreate() {
        super.onCreate();

        try {
            startService(new Intent(getApplicationContext(), AppLifeService.class));
        } catch (Throwable e) {
            e.printStackTrace();
        }

    }

}

AppLifeService.java

public class AppLifeService extends Service {

    private static final String TAG = AppLifeService.class.getSimpleName();

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d(TAG, "Service Started");
        return START_NOT_STICKY;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "Service Destroyed");
    }

    @Override
    public void onTaskRemoved(Intent rootIntent) {
        Log.e(TAG, "END");
        try {

            File cacheDir = this.getCacheDir();
            if (null != cacheDir && cacheDir.exists()) {
                forceDelete(cacheDir);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        // Stop the service itself
        stopSelf();
    }


    @SuppressWarnings("UnusedReturnValue")
    private boolean forceDelete(File file) {
        File[] contents = file.listFiles();
        if (null != contents) {
            for (File f : contents) {
                forceDelete(f);
            }
        }
        return file.delete();
    }


}

onTaskRemoved gets called when your application is terminated. so that's where you clear application cache right before app is killed.

remember to add this classes to Manifest

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.my.package"> 

    <application
        android:name=".AppController"
        android:allowBackup="true"
        android:fullBackupContent="@xml/backup_descriptor"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true">

        <service
            android:name=".AppLifeService"
            android:stopWithTask="false" />

    </application>

</manifest>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM