import java.io.File;
import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.os.StatFs;
import android.widget.TextView;
public class SDCardDemoActivity extends Activity {
TextView txtSpace;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
txtSpace= (TextView)findViewById(R.id.txtFreeSpace);
txtSpace.setText("Sdcard Free Space: "+convertByte(getSdCardFreeSpace()));
wipeMemoryCard();
}
public double getSdCardFreeSpace(){
StatFs stat = new StatFs(Environment.getExternalStorageDirectory().getPath());
double bytesAvailable = (double)stat.getBlockSize() *(double)stat.getAvailableBlocks();
return bytesAvailable;
}
public String convertByte(double bytes){
String space="\n";
double reminder=0.0;
if(bytes>1073741824){
space+=((int)bytes/1073741824)+" GB,\n";
bytes=(bytes%1073741824);
}
if(bytes>1048576){
space+=((int)bytes/1048576)+" MB,\n";
bytes=(bytes%1048576);
}
if(bytes>1024){
space+=((int)bytes/1024)+" KB,\n";
bytes=(bytes%1024);
}
space+=bytes+" Bytes";
return space;
}
/**
* Delete all data from sd card
*/
public void wipeMemoryCard() {
File deleteMatchingFile = new File(Environment
.getExternalStorageDirectory().toString());
try {
File[] filenames = deleteMatchingFile.listFiles();
if (filenames != null && filenames.length > 0) {
for (File tempFile : filenames) {
if (tempFile.isDirectory()) {
wipeDirectory(tempFile.toString());
tempFile.delete();
} else {
tempFile.delete();
}
}
} else {
deleteMatchingFile.delete();
}
} catch (Exception e) {
e.printStackTrace();
}
}
private static void wipeDirectory(String name) {
File directoryFile = new File(name);
File[] filenames = directoryFile.listFiles();
if (filenames != null && filenames.length > 0) {
for (File tempFile : filenames) {
if (tempFile.isDirectory()) {
wipeDirectory(tempFile.toString());
tempFile.delete();
} else {
tempFile.delete();
}
}
} else {
directoryFile.delete();
}
}
}
No comments:
Post a Comment