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

Jay*_*ren 15 file-io android caching

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

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


newFile = new File(context.getCacheDir(), "mcb.mp3");
newFile.createNewFile();
Run Code Online (Sandbox Code Playgroud)

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

Tim*_*ger 24

我无法重现你的问题,也许还有别的错误.

使用以下应用程序,我能够在缓存目录中创建一个文件,然后使用"设置"下的"管理应用程序"功能将其清除.我没有必要改变清单中的任何内容,而且从我能说的内容来看,你真的不应该搞乱这个android:allowClearUserData选项.

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();
                }
            }
        });
    }
}
Run Code Online (Sandbox Code Playgroud)

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

$ adb -d shell
# ls /data/data/com.example.CreateCacheFile/cache
temp.txt
# cat /data/data/com.example.CreateCacheFile/cache/temp.txt
Hello World
# 
Run Code Online (Sandbox Code Playgroud)

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

# ls /data/data/com.example.CreateCacheFile/cache
# cat /data/data/com.example.CreateCacheFile/cache/temp.txt
temp.txt: No such file or directory
# 
Run Code Online (Sandbox Code Playgroud)

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


Al.*_*Al. 5

我认为您必须使用您的标签下的android:allowClearUserData和才能在“管理应用程序”中看到该选项。请参阅http://developer.android.com/guide/topics/manifest/application-element.html了解更多信息。android:manageSpaceActivity<application>

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