android 想调用upload方法后,文件上传成功后就删除该文件。但是delfile()没有有作用。
private Handler handler = new Handler() {
public void handleMessage(android.os.Message msg) {
if (msg.arg1 == 100) {// 提示用户上传完成
delFile(Path);
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//initProgressDialog();
button2 = (Button) findViewById(R.id.button2);
button2.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
upLoad(arg0);
}
});
}
public void upLoad(View v) {
if (Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED)) {
// toast("上传");
String sdcardPath = Environment.getExternalStorageDirectory()
.getAbsolutePath();
filePath = sdcardPath + "/Abook/";
File file = new File(filePath);
//这里我选的是Abook文件夹下第五个文件上传,得根据自己的实际情况来,否则肯定出错。
fileName = file.list()[0];
filePath += fileName;
}
new Thread() {
@Override
public void run() {
try {
Thread.sleep(2000);
String response = HttpUtil.sendFile(urlString, filePath,
fileName, MainActivity.this);
Log.i("response", "response" + response);
//file.delete();
} catch (Exception e) {
e.printStackTrace();
}
}
}.start();
}
//for(i=0;i<5;i++){
/*fileName = file.list()[i];
filePath += fileName;
new Thread() {
public void run() {
try {
String response = HttpUtil.sendFile(urlString, filePath,
fileName, MainActivity.this);
Log.i("response", "response" + response);
} catch (Exception e) {
e.printStackTrace();
}
};
}.start();
}*/
/*else {
toast("没有内存卡");
return;
}
}*/
public void delFile(String filePath){
if (Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED)) {
// toast("上传");
String sdcardPath = Environment.getExternalStorageDirectory()
.getAbsolutePath();
Path = sdcardPath + "/Abook/";
File root = new File(Path );
final File[] files = root.listFiles();
files[0].delete();
}
}
/*new Thread() {
public void run() {
try {
String response = HttpUtil.sendFile(urlString, filePath,
fileName, MainActivity.this);
Log.i("response", "response" + response);
} catch (Exception e) {
e.printStackTrace();
}
};
}.start();*/
public void toast(String text) {
Toast.makeText(getApplicationContext(), text, Toast.LENGTH_SHORT)
.show();
}
@Override
public void onUpload(double process) {
process = process * 100;
int currentProcess = (int) process;
// 避免重复发消息,可以把if给去掉看看会发生什么
if (currentProcess > oldProcess) {
Message msg = handler.obtainMessage();
msg.arg1 = (int) process;
handler.sendMessage(msg);
}
oldProcess = currentProcess;
}
}
确定上传的流是否已关闭?