如何在Xamarin android mono中以编程方式清除应用程序的捕获数据

7fhtutme  于 2023-04-27  发布在  Android
关注(0)|答案(1)|浏览(98)

我已经尝试使用下面的代码,我能够得到的捕获文件的路径,但无法删除路径或该路径中的数据.下面是我使用的代码来做到这一点.

public void clearApplicationData()
        {
            var tmpdir = System.IO.Path.GetTempPath();
             File applicationDirectory = new File(tmpdir);
              if (applicationDirectory != null && applicationDirectory.Exists())
            {
                //deleteFile(applicationDirectory);
                string[] fileNames = applicationDirectory.List();
                foreach (string fileName in fileNames)
                {
                    if (!fileNames.Equals("lib"))
                    {
                        deleteFile(new File(applicationDirectory, fileName));
                    }
                }
            }
        }
 public static bool deleteFile(File file)
        {
            bool deletedAll = false;
            if (file != null)
            {
                if (file.IsDirectory)
                {
                    string[] children = file.List();
                    for (int i = 0; i < children.Length; i++)
                    {
                        deletedAll = deleteFile(new File(file, children[i])) && deletedAll;
                    }
                }
                else
                {
                    file.DeleteOnExit();
                    deletedAll = file.Exists();
                }
            }

            return deletedAll;
        }

我还添加了CLEAR_APP_CATCH,CLEAR_APP_USER_DATA的权限请帮助我这样做,我愿意清除完整的应用程序的现金和数据,并在结束时,我愿意重新启动应用程序,以显示登录页面或结束应用程序。

uqzxnwby

uqzxnwby1#

这将立即清除所有数据和缓存。它将关闭应用程序并释放内存。

((ActivityManager)Application.Context.GetSystemService(ActivityService)).ClearApplicationUserData();

如果你不想这样,你可以试试下面的代码。
另外,我建议您使用System.IO文件实用程序,而不是Java.IO文件实用程序。

try
{
    var cachePath = System.IO.Path.GetTempPath();

    // If exist, delete the cache directory and everything in it recursivly
    if (System.IO.Directory.Exists(cachePath))
        System.IO.Directory.Delete(cachePath, true);

    // If not exist, restore just the directory that was deleted
    if (!System.IO.Directory.Exists(cachePath))
        System.IO.Directory.CreateDirectory(cachePath);
}
catch(Exception){}

您可以尝试同样的操作来删除应用程序数据,方法是使用

var dataPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments);

代替cachePath,但请记住,您的应用可能会表现得很滑稽,因为它仍然在堆内存中有信息,并且缺少相应的文件。例如,除此之外,您可能还希望清除SharedPrefs。

相关问题