Android--Clean up your phone's SD card cache

Source: Internet
Author: User

Reprint Please specify source: http://blog.csdn.net/l1028386804/article/details/47375595

At present, many Android phone software in the market has the function of clearing SD card cache, such as 360, Jinshan and so on. So how does the software implement the ability to clean up the SD card cache data? Below, I will show you how these features are implemented.

First, the principle

First of all, let's talk about the principle of this feature implementation.

In the Android phone, some of the commonly used application cache directory, all in a database table, the table in the directory query to put in a list set, we will temporarily define the list as paths, then we go to the SD card to get all the file directory, Traverse all the file directories under the SDK, and if paths contains a directory, recursively delete the directory file.

The principle is too long-winded, very simple, then let us together to achieve these functions.

Second, the realization

Implementation is divided into two steps, database preparation and code implementation

1. Database Preparation

This example uses a database clearpath.db that holds the application cache directory, first placing the database in the assets directory of the Application project

2. Code implementation

In this example, I write this function code into a method written in mainactivity, we mainly analyze each method in this class can be.

1) How to copy a database Copydb

The function of this method is to copy the database under the assets directory to the/data/data/application package name/files directory, and return the database file object.

The specific implementation code is as follows:

/** * Copy the database and return the database file object * @return */private files Copydb () {//Copy the database to the files directory file File = new file (Getfilesdir (), "clearpath.db "), if (!file.exists ()) {try {InputStream in = Getassets (). Open (" Clearpath.db "), outputstream out = new FileOutputStream ( file); byte[] buffer = new Byte[1024];int len = 0;while (len = in.read (buffer))! =-1) {out.write (buffer, 0, Len);} Out.close (); In.close ();} catch (Exception e) {e.printstacktrace ();}} return file;}

2) Get the collection of file directories in the database to be cleaned getpaths

The function of this method is to call the Copydb method to copy the database, retrieve the database file object, query all the file directories stored in the database, and encapsulate those directories in a list collection to return.

The specific code is implemented as follows:

/** * Get directory collection of files to be cleaned in database * @return */private list<string> getpaths () {//Copy database list<string >list = new ARRAYLIST&L T String> (); File File = Copydb (), if (file! = null) {Sqlitedatabase db = Sqlitedatabase.opendatabase (File.getabsolutepath (), NULL, SQLITEDATABASE.OPEN_READONLY); if (Db.isopen ()) {Cursor c = db.query ("Softdetail", New string[]{"filepath"}, NULL, NULL, NULL, NULL, NULL), while (C.movetonext ()) {String path = c.getstring (C.getcolumnindex ("filepath")), List.add (path); C.close ();d b.close ();}} return list;}

3) Delete files recursively

This method mainly implements the operation of the recursive delete file, first traversing the file directory, if the current file is a directory, then traverse the subdirectory, continue to call its own Delete method, if it is a file, then call file's Delete method.

The specific implementation code is as follows:

/** * Recursively Delete files * @param file */private void Delete (file file) {if (File.isdirectory ()) {file[] files = file.listfiles (); for (Fil E f:files) {delete (f);}} Else{file.delete ();}}

4) Get the file collection paths

We define a global list collection paths, and call the Getpaths method in the OnCreate method to assign a value to the collection. In this case, all the file paths in the database are encapsulated in this collection. The reason we define paths as a global variable and call the Getpaths method in the OnCreate method to assign it is to improve performance. Because reading data from a database is a performance-intensive operation, this method is performed only once in OnCreate, avoiding the one-click button once in a click event. This significantly improves the performance of the application.

The specific implementation code is as follows:

private list<string> paths; @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate ( Savedinstancestate); Setcontentview (r.layout.activity_main);p aths = This.getpaths ();}

5) button click event ClearData

This method mainly responds to the button's Click event, implements the function of clearing the cache, where we put the cleanup function in a sub-thread to execute, through the looper mechanism to remind the user to clean up the completion.

The specific code is implemented as follows:

button click event public void ClearData (View v) {New Thread (new Runnable () {@Overridepublic void Run () {//TODO auto-generated method Stubfile file = new file (Environment.getexternalstoragedirectory (). GetAbsolutePath ()); file[] files = file.listfiles (); if (Files! = null && files.length > 0) {for (file f:files) {String name = "/" + F . GetName ();//paths the collection contains Nameif (Paths.contains (name)) {delete (f);}}} Looper.prepare (); Toast.maketext (Mainactivity.this, "SD card cache cleanup Complete", Toast.length_short). Show (); Looper.loop ();}}). Start ();}

6) mainactivity Overall implementation code

Package Com.lyz.test.cache;import Java.io.file;import Java.io.fileoutputstream;import java.io.InputStream;import Java.io.outputstream;import Java.util.arraylist;import Java.util.list;import Android.app.activity;import Android.database.cursor;import Android.database.sqlite.sqlitedatabase;import Android.os.Bundle;import Android.os.environment;import Android.os.looper;import Android.view.menu;import Android.view.View;import android.widget.toast;/** * Main program entry * @author Liuyazhuang * */public class Mainactivity extends Activity {private list<str ing> paths; @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (r.layout.activity_main);p aths = This.getpaths ();} @Overridepublic boolean Oncreateoptionsmenu (Menu menu) {//Inflate the menu; This adds items to the action bar if it is PR Esent.getmenuinflater (). Inflate (R.menu.main, menu); return true;} button click event public void ClearData (View v) {New Thread (new Runnable () {@Overridepublic void run () {TODO auto-generated method Stubfile file = new file (Environment.getexternalstoragedirectory (). GetAbsolutePath ()); file[] files = file.listfiles (); if (Files! = null && files.length > 0) {for (file f:files) {String name = "/" + F . GetName ();//paths the collection contains Nameif (Paths.contains (name)) {delete (f);}}} Looper.prepare (); Toast.maketext (Mainactivity.this, "SD card cache cleanup Complete", Toast.length_short). Show (); Looper.loop ();}}). Start ();} /** * Recursively Delete files * @param file */private void Delete (file file) {if (File.isdirectory ()) {file[] files = file.listfiles (); for (Fil E f:files) {delete (f);}} Else{file.delete ();}} /** * Copy the database and return the database file object * @return */private files Copydb () {//Copy the database to the files directory file File = new file (Getfilesdir (), "clearpath.db "), if (!file.exists ()) {try {InputStream in = Getassets (). Open (" Clearpath.db "), outputstream out = new FileOutputStream ( file); byte[] buffer = new Byte[1024];int len = 0;while (len = in.read (buffer))! =-1) {out.write (buffer, 0, Len);} Out.close (); In.close ();} catch (Exception e) {e.printstacktRace ();}} return file;} /** * Get directory collection of files to be cleaned in database * @return */private list<string> getpaths () {//Copy database list<string >list = new ARRAYLIST&L T String> (); File File = Copydb (), if (file! = null) {Sqlitedatabase db = Sqlitedatabase.opendatabase (File.getabsolutepath (), NULL, SQLITEDATABASE.OPEN_READONLY); if (Db.isopen ()) {Cursor c = db.query ("Softdetail", New string[]{"filepath"}, NULL, NULL, NULL, NULL, NULL), while (C.movetonext ()) {String path = c.getstring (C.getcolumnindex ("filepath")), List.add (path); C.close ();d b.close ();}} return list;}}

7) Layout File Activity_main

This layout is very simple, we just put a button.

The specific implementation code is as follows:

<relativelayout xmlns:android= "http://schemas.android.com/apk/res/android"    xmlns:tools= "http// Schemas.android.com/tools "    android:layout_width=" match_parent "    android:layout_height=" Match_parent "    android:paddingbottom= "@dimen/activity_vertical_margin"    android:paddingleft= "@dimen/activity_ Horizontal_margin "    android:paddingright=" @dimen/activity_horizontal_margin "    android:paddingtop=" @dimen /activity_vertical_margin "    tools:context=". Mainactivity ">    <button        android:layout_width=" match_parent "        android:layout_height=" Wrap_ Content "        android:onclick=" ClearData "        android:text=" cleans SD card data "/></relativelayout>

3. Application authorization

Here, we want to clear the SD card data, all to the write SD card authorization, we add the following authorization information in the Androidmanifest.xml file

<uses-permission android:name= "Android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/><uses-permission android: Name= "Android.permission.WRITE_EXTERNAL_STORAGE"/>

Third, the Operation effect

Four, warm tips

Everyone can go to link http://download.csdn.net/detail/l1028386804/8980767 download android clean SD card Cache database file, can go to link http://download.csdn.net/ detail/l1028386804/8980789 download Android clean SD card Cache complete sample source code

In this example, for the sake of the aspect, I write some text directly in the layout file and the related class, Everyone in the real project to write these words in the String.xml file, in the external reference to these resources, remember, this is the most basic development knowledge and specifications as an Android programmer, I am here just to facilitate directly written in the class and layout files.

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Android--Clean up your phone's SD card cache

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.