如何利用Android的“清除缓存”按钮

时间:2010-05-17 12:12:29

标签: android caching file-io

在Android的设置中,在单击应用程序时的“管理应用程序”活动中,数据会分解为应用程序,数据和缓存。还有一个清除缓存的按钮。我的应用程序缓存音频文件,我希望用户能够使用此按钮清除缓存。如何存储它们以便它们与缓存混在一起并且用户可以清除它们?我尝试使用以下两种技术存储文件:

newFile = File.createTempFile("mcb", ".mp3", context.getCacheDir());


newFile = new File(context.getCacheDir(), "mcb.mp3");
newFile.createNewFile();

在这两种情况下,这些文件都列为数据而不是缓存。

2 个答案:

答案 0 :(得分:24)

我无法重现您的问题,也许还有其他错误。

使用以下应用程序,我能够在缓存目录中创建一个文件,然后使用“设置”下的“管理应用程序”功能将其清除。我不需要改变清单中的任何内容,也不必改变我所知道的内容you really shouldn't mess with the android:allowClearUserData option

public class CreateCacheFile extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        Button button = (Button) findViewById(R.id.CreateFileButton);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                File file = new File(
                        CreateCacheFile.this.getCacheDir(), "temp.txt");

                try {
                    file.createNewFile();
                    FileWriter fw = new FileWriter(file);
                    BufferedWriter bw = new BufferedWriter(fw);
                    bw.write("Hello World");
                    bw.newLine();
                    bw.close();

                } catch (IOException e) {
                    Toast.makeText(
                            CreateCacheFile.this, 
                            "Error!", 
                            Toast.LENGTH_SHORT).show();
                }
            }
        });
    }
}

运行应用程序后(单击按钮创建文件):

$ adb -d shell
# ls /data/data/com.example.CreateCacheFile/cache
temp.txt
# cat /data/data/com.example.CreateCacheFile/cache/temp.txt
Hello World
# 

管理应用程序报告有4KB空间用于缓存。单击按钮清除它后:

# ls /data/data/com.example.CreateCacheFile/cache
# cat /data/data/com.example.CreateCacheFile/cache/temp.txt
temp.txt: No such file or directory
# 

此时,管理应用程序报告正在使用0KB的空间用于缓存。

答案 1 :(得分:4)

我认为您必须使用android:allowClearUserData标记下的android:manageSpaceActivity<application>来查看“管理应用”中的该选项。有关详细信息,请参阅http://developer.android.com/guide/topics/manifest/application-element.html

或者,可以选择在活动中清除缓存。

相关问题