首页 > 解决方案 > 如何在退出按下按钮时清除应用程序缓存?

问题描述

我只想在按下退出时清除应用程序缓存,尝试了很多答案,但出现错误并且不起作用,所以这是我的代码:

if (Config.ENABLE_EXIT_DIALOG) {

            AlertDialog.Builder dialog = new AlertDialog.Builder(MainActivity.this);
            dialog.setIcon(R.mipmap.ic_launcher);
            dialog.setTitle(R.string.app_name);
            dialog.setMessage(R.string.dialog_close_msg);
            dialog.setPositiveButton(R.string.dialog_option_yes, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    MainActivity.this.finish();
                }
            });

            dialog.setNegativeButton(R.string.dialog_option_rate_us, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    final String appName = getPackageName();
                    try {
                        startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + appName)));
                    } catch (android.content.ActivityNotFoundException anfe) {
                        startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://play.google.com/store/apps/details?id=" + appName)));
                    }

                    MainActivity.this.finish();
                }
            });

            dialog.setNeutralButton(R.string.dialog_option_more, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(getString(R.string.play_more_apps))));

                    MainActivity.this.finish();
                }
            });
            dialog.show();

        } else {
            super.onBackPressed();
        }

标签: javaandroidcaching

解决方案


解决了,我认为这是旧方法,但工作正常在这里找到它 我实际上在我的 mainActivity 文件末尾使用了他的问题代码,它就像一个魅力,虽然我猜这是一种旧方法,但没关系。这是代码

@Override
protected void onDestroy() {
    // TODO Auto-generated method stub
    super.onDestroy();
    clearApplicationData();
}

public void clearApplicationData() {
    File cache = getCacheDir();
    File appDir = new File(cache.getParent());
    if (appDir.exists()) {
        String[] children = appDir.list();
        for (String s : children) {
            if (!s.equals("lib")) {
                deleteDir(new File(appDir, s));
                Log.i("EEEEEERRRRRRROOOOOOORRRR", "**************** File /data/data/APP_PACKAGE/" + s + " DELETED *******************");
            }
        }
    }
}

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;
            }
        }
    }

    return dir.delete();
}

推荐阅读