1. Because you need to delete files, you need the following permissions:
<uses-permission android:name= "Android.permission.WRITE_EXTERNAL_STORAGE" ></uses-permission>
2. Core Code
Copy Code code as follows:
Package Com.example.deleteyoumi;
Import Java.io.File;
Import Android.os.Bundle;
Import Android.os.Handler;
Import Android.os.Message;
Import android.app.Activity;
Import Android.view.Menu;
Import Android.view.View;
Import Android.view.View.OnClickListener;
Import Android.widget.Button;
Import Android.widget.Toast;
/*
* @author: Zhenghaibo
*web:http://blog.csdn.net/nuptboyzhb
*mail:zhb931706659@126.com
*2013-4-28 Nanjing,njupt,china
*/
public class Deleteyoumimainactivity extends activity implements
Onclicklistener {
Private Button DeleteButton;
Private final static String youmipathstring = "/mnt/sdcard/android/data/.youmicache/";//Path to Folder
@Override
protected void OnCreate (Bundle savedinstancestate) {
Super.oncreate (savedinstancestate);
Setcontentview (R.layout.activity_delete_you_mi_main);
DeleteButton = (Button) Findviewbyid (R.id.delete_youmi);
Deletebutton.setonclicklistener (this);
}
@Override
public boolean Oncreateoptionsmenu (Menu menu) {
Inflate the menu; This adds items to the action bar if it is present.
Getmenuinflater (). Inflate (R.menu.delete_you_mi_main, menu);
return true;
}
@Override
public void OnClick (View v) {
TODO auto-generated Method Stub
Switch (V.getid ()) {
Case R.id.delete_youmi:
File File = new file (youmipathstring);
DeleteFile (file);
Mhandler.sendemptymessage (1);
Break
Default
Break
}
}
Handler Mhandler = new Handler () {
public void Handlemessage (msg) {
Switch (msg.what) {
Case 0:
Toast.maketext (Getapplicationcontext (), "file or folder does not exist", Toast.length_long). Show ();
Break
Case 1:
Toast.maketext (Getapplicationcontext (), "Delete success!" ", Toast.length_long). Show ();
Break
Default
Break
}
};
};
/**
* Recursively delete files and folders
*
* @param file
* The root directory to be deleted
*/
public void DeleteFile (file file) {
if (file.exists () = = False) {
Mhandler.sendemptymessage (0);
Return
} else {
if (File.isfile ()) {
File.delete ();
Return
}
if (File.isdirectory ()) {
file[] Childfile = File.listfiles ();
if (Childfile = null | | childfile.length = 0) {
File.delete ();
Return
}
for (File f:childfile) {
DeleteFile (f);
}
File.delete ();
}
}
}
}
3. Expand
This article is to remove the example. Of course, this method is available for traversing all files under a folder. such as search for. mp3 files.