Android ftpベースのリモートファイル管理
最近、会社のプロジェクトにはリモートファイル管理の内容があり、ネットで調べたところ、ほとんどがftpに基づいて実現されていることが分かったが、半日探しても適切な例が見つからず、最後にグループの学生の助けを得て成功した.
私はプロジェクトを簡単にまとめて、みんなが勉強して使うようにしました.
Android端はサードパーティjarパッケージのサポートを導入する必要があります.私がここで選んだのはapache公式のcommons-net-3.2.jarです.解凍してjarパッケージを導入すればいいです.すでにアップロードされています.
http://download.csdn.net/detail/yudajun/5140914
主なコードは次のとおりです.
account.java
FtpBrowserActivity2.java
以上のコードは十分に研究を学んで、サーバーは自分で探して、すでにアップロードしました
http://download.csdn.net/detail/yudajun/5140876
分からないことがあれば、伝言を残して交流してください.
2014/4/25更新、詳細コードアップロード
クリックしてリンクを開く
私はプロジェクトを簡単にまとめて、みんなが勉強して使うようにしました.
Android端はサードパーティjarパッケージのサポートを導入する必要があります.私がここで選んだのはapache公式のcommons-net-3.2.jarです.解凍してjarパッケージを導入すればいいです.すでにアップロードされています.
http://download.csdn.net/detail/yudajun/5140914
主なコードは次のとおりです.
package com.ftpbrowser.sample;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.SocketException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Toast;
public class FtpFileManage {
private final String tag="fileManageLog";
private final static String REFRESH_PATH = "start_path";
private final static String CHANGE_FILE_PATH = "change_path";
private final static String DELETE_FILE = "delete_file";
private final static String UPLOAD_FILE = "upload_file";
private final static String DOWNLOAD_FILE = "download_file";
private final static String COPY_FILE = "copy_file";
private final static String MOVE_FILE = "move_file";
private final static String dirChar = File.separator;
private static String FTP_DEFAULT_CODE = "ISO-8859-1";
private final static String GBK = "GBK";
private final static String UTF = "UTF-8";
private final static String TEMP_FILE_DIR = FtpBrowserActivity2.STORE_DIRECTORY + "/_temp";
private List<FtpFileInfo> mFilesInfo;
private List<String> mStackNowPath;
private List<FtpFileInfo> mCheck4Paste;
private static FtpFileManage instance = null;
private static FTPClient ftpClient = null;
FtpBrowserActivity2 browserActivity;
private FtpFileManage(){
mFilesInfo=new ArrayList<FtpFileInfo>();
mStackNowPath=new ArrayList<String>();
mCheck4Paste = new ArrayList<FtpFileInfo>();
mStackNowPath.add(dirChar);
ftpClient = new FTPClient();
FTP_DEFAULT_CODE = ftpClient.getControlEncoding();
}
public static synchronized FtpFileManage getInstance(){
if(null==instance){
instance=new FtpFileManage();
}
return instance;
}
public void setActivity(){
this.browserActivity=FtpBrowserActivity2.browserActivity;
}
/**
*
* @return
*/
public List<FtpFileInfo> getlistFilesInfo(){
return this.mFilesInfo;
}
/**
*
*/
public void startListPath(){
FileManageTask task=new FileManageTask(browserActivity);
task.execute(new String[]{REFRESH_PATH});
}
/**
*
* @param path
*/
private void changeWorkingDir(String path){
FileManageTask task=new FileManageTask(browserActivity);
task.execute(new String[]{CHANGE_FILE_PATH,path});
}
/**
*
* @param context
* @param pathData
*/
public void uploadFile(ArrayList<String> pathData) {
FileManageTask task=new FileManageTask(browserActivity);
task.setFilePath(pathData);
task.execute(new String[]{UPLOAD_FILE});
}
/**
*
* @param context
* @param pathData
*/
public void downLoadFile(String pathData) {
FileManageTask task=new FileManageTask(browserActivity);
task.execute(new String[]{DOWNLOAD_FILE,pathData});
}
/**
*
*/
public void deleteFile(){
FileManageTask task=new FileManageTask(browserActivity);
task.execute(new String[]{DELETE_FILE});
}
/**
*
* @return
*/
public boolean copy() {
if(mCheck4Paste.size()>0)
mCheck4Paste.clear();
for(FtpFileInfo ftpFileInfo : mFilesInfo){
if(ftpFileInfo.isChecked()){
mCheck4Paste.add(ftpFileInfo);
}
}
return false;
}
/**
*
* @param isMoveFile
*/
public void paste(boolean isMoveFile) {
// ArrayList<String> fileNames = new ArrayList<String>();
String path = mCheck4Paste.get(0).getFilePath();
/*for(FileInfo files : mCheck4Paste){
fileNames.add(files.getFileRAWName());
}*/
if(isMoveFile){
FileManageTask task=new FileManageTask(browserActivity);
task.setFileInfo((ArrayList<FtpFileInfo>)mCheck4Paste);
task.execute(new String[]{MOVE_FILE,path,getNowLoadingPath()});
}else{
FileManageTask task=new FileManageTask(browserActivity);
task.setFileInfo((ArrayList<FtpFileInfo>)mCheck4Paste);
task.execute(new String[]{COPY_FILE,path,getNowLoadingPath()});
}
}
/**
*
* @return
*/
public boolean move() {
if(mCheck4Paste.size()>0)
mCheck4Paste.clear();
for(FtpFileInfo ftpFileInfo : mFilesInfo){
if(ftpFileInfo.isChecked()){
mCheck4Paste.add(ftpFileInfo);
}
}
return true;
}
/**
* ftp
* @param params
* @return
*/
public boolean connectClient(String... params){
boolean isSuccess = false;
try {
ftpClient.setConnectTimeout(20000);
ftpClient.connect(params[0]);
// ftpClient.connect(params[1],Integer.parseInt(params[2]));
ftpClient.enterLocalPassiveMode();
int reply;
reply = ftpClient.getReplyCode();
if (FTPReply.isPositiveCompletion(reply)) {
if (ftpClient.login(params[1], params[2])) {
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
ftpClient.setSoTimeout(20000);
ftpClient.setDataTimeout(20000);
ftpClient.setFileTransferMode(FTPClient.ACTIVE_LOCAL_DATA_CONNECTION_MODE);
ftpClient.setDefaultTimeout(20000);
Log.d(tag, "ftp server connector succuss");
return true;
}
}
ftpClient.disconnect();
} catch (SocketException e) {
Log.e(tag, "ftp connect error");
/*Message m=browserActivity.mHandler.obtainMessage(FtpBrowserActivity2.EMPTY_DATA, "connect ftpServer fail");
m.sendToTarget();*/
} catch (IOException e) {
Log.e(tag, "ftp login fail");
}
return isSuccess;
}
/**
*
* @param files
*/
private void getClientFiles(FTPFile[] files){
if(mFilesInfo.size()>0)
mFilesInfo.clear();
SimpleDateFormat sdFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
int length = files.length;
for(int i = 0; i<length; i++){
FTPFile file = files[i];
FtpFileInfo ftpFileInfo = new FtpFileInfo();
String str = file.getName();
try {
str = new String(str.getBytes(FTP_DEFAULT_CODE),GBK);
} catch (UnsupportedEncodingException e) {
Log.e(tag, e.getMessage());
}
ftpFileInfo.setFileName(str);
ftpFileInfo.setFileRAWName(file.getName());
try {
ftpFileInfo.setFilePath(ftpClient.printWorkingDirectory());
} catch (IOException e) {
Log.e(tag, e.getMessage());
}
ftpFileInfo.setDirectory(file.isDirectory());
if(file.isDirectory()){
ftpFileInfo.setFileSize("");
}else{
ftpFileInfo.setFileSize(String.valueOf(file.getSize()));
}
Date date = file.getTimestamp().getTime();
ftpFileInfo.setLastModified(String.valueOf(sdFormat.format(date)));
ftpFileInfo.setFtpFile(file);
mFilesInfo.add(ftpFileInfo);
}
}
/**
* ftp
*/
public void disConnectClient() {
if(null == ftpClient)return;
try {
ftpClient.disconnect();
} catch (IOException e) {
Log.e(tag, "ftp close fail");
}
}
/**
*
* @param keyCode
* @param event
* @return
*/
public boolean onKeyUp(int keyCode, KeyEvent event) {
// if(keyCode == KeyEvent.KEYCODE_BACK){
return onKeyBackEvent();
// }
// return false;
}
/**
*
* @return
*/
private boolean onKeyBackEvent(){
int stackSize = mStackNowPath.size();
if(stackSize <= 1){
//activity.finish and ftp close
disConnectClient();
browserActivity.finish();
}else{
mStackNowPath.remove(stackSize - 1);
String path = "";
for(String str : mStackNowPath){
path += str;
}
changeWorkingDir(path);
}
return false;
}
/**
* item
* @param position
*/
public void onItemClickListener(int position) {
FTPFile ftpFile = mFilesInfo.get(position).getFtpFile();
if(ftpFile.isDirectory()){
changeWorkingDir(position);
}else{
//to open it
}
}
public void onItemLongClick(int arg2) {
}
/**
*
* @return
*/
private String getNowLoadingPath(){
String allPath = "";
try {
allPath += ftpClient.printWorkingDirectory();
} catch (IOException e) {
Log.e(tag, e.getMessage());
}
if(!allPath.endsWith(dirChar)){allPath += dirChar;}
return allPath;
}
/**
*
* @param item
*/
private void changeWorkingDir(int item){
String itemFileName = mFilesInfo.get(item).getFileRAWName() + dirChar ;
mStackNowPath.add(itemFileName);
changeWorkingDir(itemFileName);
}
/**
* ftp
* @param uploadFilePath
* @param remoteFilePath
*/
private boolean uploadFiles(FTPClient ftp,String uploadFilePath,String remoteFilePath){
boolean isSuccess = false;
InputStream local = null;
try {
if (ftp.listFiles(remoteFilePath) == null || ftp.listFiles(remoteFilePath).length == 0) {
ftp.makeDirectory(remoteFilePath);
Log.e(tag, "create file : " + remoteFilePath);
}
local = new FileInputStream(uploadFilePath);
String str [] = uploadFilePath.split(dirChar);
int length = str.length;
String fileName = str[length - 1];
isSuccess = ftp.storeFile(fileName, local);
} catch (FileNotFoundException e) {
Log.e(tag, "not found uploadFile error");
}catch (IOException e) {
Log.e(tag, "file upload inputstream error");
}finally{
if(null != local){
try {
local.close();
} catch (IOException e) {
Log.e(tag, "upload inputstream close error");
}
}
}
String str = "";
if(isSuccess){
str = "upload file success!";
}else{
str = "upload file failed!";
}
Log.d(tag, str);
return isSuccess;
}
/**
* ftp
* @param ftp
* @param fileName
* @param filePaths
* @param localPath
* @return
*/
private boolean downloadFiles(FTPClient ftp,String fileName,String filePaths,String localPath) {
boolean success = false;
OutputStream out=null;
try {
int reply;
reply = ftp.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftp.disconnect();
return success;
}
/*String filePath = localPath + fileName;
File localFile = new File(localPath);
if(!localFile.exists()){localFile.mkdirs();}*/
File localFileDir=new File(localPath);
if(!localFileDir.exists()) {localFileDir.mkdir();}
String filePath = localPath +dirChar+ fileName;
File localFile = new File(filePath);
if(!localFile.exists()){localFile.createNewFile();}
out = new FileOutputStream(localFile);
ftp.retrieveFile(filePaths, out);
success = true;
} catch (IOException e) {
Log.e(tag, "dnException= "+e.getMessage());
}finally{
if(out!=null){
try {
out.close();
} catch (IOException e) {
Log.e(tag, "dn outstream close dn error");
}
}
}
String str = "";
if(success){
str = "dnload file success!";
}else{
str = "dnload file failed!";
}
Log.d(tag, str);
return success;
}
/**
*
* @param ftp
* @return
*/
private boolean deleteFiles(FTPClient ftp){
boolean success = false;
FileAdapter adapter = browserActivity.getFileAdapter();
List<FtpFileInfo> listChecked = adapter.getCheckedListFiles();
// List<FtpFileInfo> listChecked=FileInfo.checkListInfo;
if(null == listChecked || listChecked.size() <= 0){
return success;
}
String nowPath = getNowLoadingPath();
for(FtpFileInfo ftpFileInfo : listChecked){
String fileName = nowPath + ftpFileInfo.getFileRAWName();
try {
success = ftp.deleteFile(fileName);
} catch (IOException e) {
Log.e(tag, "delete file error");
}
}
String str = "";
if(success){
str = "delete file success!";
}else{
str = "delete file failed!";
}
Log.d(tag, str);
return success;
}
/**
*
* @param pos
*/
public void deleteOneFile(int pos){
boolean success=false;
FtpFileInfo ftpFileInfo=mFilesInfo.get(pos);
String nowPath = getNowLoadingPath();
String fileName = nowPath + ftpFileInfo.getFileRAWName();
try {
success = ftpClient.deleteFile(fileName);
} catch (IOException e) {
Log.e(tag, "delete file error");
}
String str = "";
if(success){
str = "delete file success!";
}else{
str = "delete file failed!";
}
Message msg=browserActivity.mHandler.obtainMessage(FtpBrowserActivity2.EMPTY_DATA, str);
msg.sendToTarget();
browserActivity.mHandler.sendEmptyMessage(FtpBrowserActivity2.REFRESH_DATA);
}
private boolean copyFiles(FTPClient ftp,String oldDir,FTPFile ftpFile,String fileName,String remotePath){
boolean success = false;
try {
File localFileDir=new File(TEMP_FILE_DIR);
if(!localFileDir.exists()) {localFileDir.mkdir();}
String tempFilePath = TEMP_FILE_DIR +dirChar+ fileName;
File localFile = new File(tempFilePath);
if(!localFile.exists()){localFile.createNewFile();}
OutputStream out = new FileOutputStream(localFile);
ftp.retrieveFile(oldDir+ftpFile.getName(), out);//down
out.close();
// ftp.changeWorkingDirectory(remotePath);
InputStream local = new FileInputStream(localFile);
success = ftp.storeFile(remotePath+fileName,local);//upload
local.close();
// ftp.changeWorkingDirectory(oldDir);
localFile.delete();
} catch (IOException e) {
success = false;
Log.e(tag, "copy file error");
}
String str = "";
if(success){
str = "copy file success!";
}else{
str = "copy file failed!";
}
Log.d(tag, str);
return success;
}
/**
*
* @param ftp
* @param oldDir
* @param fileName
* @param remotePath
* @return
*/
private boolean moveFiles(FTPClient ftp,String oldDir,String fileName,String remotePath){
boolean isSuccess = false;
try {
isSuccess = ftp.rename(oldDir+fileName, remotePath + fileName);
} catch (IOException e) {
isSuccess = false;
Log.e(tag, "move file error");
}
String str = "";
if(isSuccess){
str = "move file success!";
}else{
str = "move file failed!";
}
Log.d(tag, str);
return isSuccess;
}
/**
*
* @return
*/
public String oldMovePathBefore(){
String path=getNowLoadingPath();
return path;
}
/**
*
* @param pos
* @param oldDir
*/
public void moveOneFile(int pos,String oldDir){
boolean isSuccess = false;
FTPFile ftpFile=mFilesInfo.get(pos).getFtpFile();
try {
isSuccess = ftpClient.rename(oldDir+ftpFile.getName(), getNowLoadingPath() + ftpFile.getName());
} catch (IOException e) {
isSuccess = false;
Log.e(tag, "move file error");
}
String str = "";
if(isSuccess){
str = "move file success!";
}else{
str = "move file failed!";
}
Message msg=browserActivity.mHandler.obtainMessage(FtpBrowserActivity2.EMPTY_DATA, str);
msg.sendToTarget();
browserActivity.mHandler.sendEmptyMessage(FtpBrowserActivity2.REFRESH_DATA);
}
public void showFileRenameDialog(final FtpFileInfo file){
final Context context=browserActivity;
final View myView = LayoutInflater.from(context).inflate( R.layout.file_rename_dialog,null);
final EditText edt = (EditText)myView.findViewById(R.id.edtFileRename);
edt.setText(file.getFileName());
AlertDialog renameDialog = new AlertDialog.Builder(context).create();
renameDialog.setView(myView);
renameDialog.setCancelable(true);
renameDialog.setButton(context.getString(android.R.string.ok), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String newName = String.valueOf(edt.getText());
if(newName == null || newName.length() <= 0){
Toast.makeText(context, "name isn't null", Toast.LENGTH_SHORT).show();
return ;
}else{
try {
String path = file.getFilePath();
if(!path.endsWith(dirChar)){path += dirChar;}
final boolean isSuccess=ftpClient.rename(path+file.getFileRAWName(), path+newName);
String str = "";
if(isSuccess){
str = "rename file success!";
}else{
str = "rename file failed!";
}
Toast.makeText(browserActivity, str, Toast.LENGTH_SHORT).show();
browserActivity.mHandler.sendEmptyMessage(FtpBrowserActivity2.REFRESH_DATA);
} catch (IOException e) {
Log.e(tag, "rename file error");
}
}
}
});
renameDialog.setButton2(context.getString(android.R.string.cancel),
new DialogInterface.OnClickListener(){
@Override
public void onClick(DialogInterface dialog, int which){
}
});
renameDialog.show();
}
/**
*
* @author Andy
*
*/
private class FileManageTask extends AsyncTask<String, String, String>{
private ProgressDialog pgdialog;
private Context mcontext;
private List<String> filePaths;
private List<FtpFileInfo> fs;
public FileManageTask(Context mcontext){
this.mcontext=mcontext;
}
public void setFilePath(ArrayList<String> fileData){
this.filePaths = fileData;
}
public void setFileInfo(ArrayList<FtpFileInfo> fileData){
this.fs=fileData;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
if(null != pgdialog && pgdialog.isShowing())return;
pgdialog = new ProgressDialog(mcontext);
// pgdialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
pgdialog.setMessage("Please wait...");
pgdialog.setIndeterminate(true);
pgdialog.setCancelable(false);
pgdialog.show();
}
@Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
}
@Override
protected String doInBackground(String... params) {
String result = params[0];
if(REFRESH_PATH.equals(params[0])){
FTPFile[] files;
try {
files = ftpClient.listFiles();
getClientFiles(files);
} catch (IOException e) {
Log.e(tag, e.getMessage());
}
}
else if(CHANGE_FILE_PATH.equals(params[0])){
// Log.e(tag, "changeWorkingDir : " + params[1]);
try {
ftpClient.changeWorkingDirectory(params[1]);
FTPFile[] files = ftpClient.listFiles();
getClientFiles(files);
} catch (IOException e) {
Log.e(tag, e.getMessage());
}
}
else if(UPLOAD_FILE.equals(params[0])){
int size = filePaths.size();
for(int i = 0; i<size; i++){
uploadFiles(ftpClient,filePaths.get(i),getNowLoadingPath());
// Log.e(tag, filePaths.get(i) + "is uploaded.");
}
}
else if(DOWNLOAD_FILE.equals(params[0])){
FileAdapter adapter = browserActivity.getFileAdapter();
List<FtpFileInfo> listChecked = adapter.getCheckedListFiles();
if(null == listChecked || listChecked.size() <= 0){
result=null;
return result;
}
for(FtpFileInfo files : listChecked){
String path = files.getFilePath();
if(!path.endsWith(dirChar)){path += dirChar;}
downloadFiles(ftpClient,files.getFileName(),path+ files.getFileRAWName(),params[1]);
}
}
else if(DELETE_FILE.equals(params[0])){
deleteFiles(ftpClient);
}
else if(COPY_FILE.equals(params[0])){
for (FtpFileInfo oldInfo : fs) {
FTPFile oldFtpFile=oldInfo.getFtpFile();
boolean results = copyFiles(ftpClient,params[1]+dirChar,oldFtpFile,oldFtpFile.getName(),params[2]);
if(!results){result = null;}
}
}
else if(MOVE_FILE.equals(params[0])){
for (FtpFileInfo oldInfo : fs) {
FTPFile ftpFile=oldInfo.getFtpFile();
moveFiles(ftpClient,params[1]+dirChar,ftpFile.getName(),params[2]);
}
}
return result;
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if(UPLOAD_FILE.equals(result)){
doInBackground(REFRESH_PATH);
}else if(DELETE_FILE.equals(result)){
doInBackground(REFRESH_PATH);
}else if(DOWNLOAD_FILE.equals(result)){
doInBackground(REFRESH_PATH);
}else if(COPY_FILE.equals(result)){
doInBackground(REFRESH_PATH);
}else if(MOVE_FILE.equals(result)){
doInBackground(REFRESH_PATH);
}
browserActivity.mHandler.sendEmptyMessage(FtpBrowserActivity2.REFRESH_DATA);
pgdialog.dismiss();
}
@Override
protected void onCancelled() {
super.onCancelled();
pgdialog.dismiss();
}
}
}
account.java
package com.ftpbrowser.sample;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.Toast;
public class FtpAccount {
private String tag = "FtpAccounts";
private Context mContext;
//view
private EditText mEdtFTPDialogAddress;
private EditText mEdtFTPDialogPort;
private EditText mEdtFTPDialogUserName;
private EditText mEdtFTPDialogPWD;
private Button mBtnDialogOK;
private View inflaterView;
private FtpUtils ftpUtil;
public FtpAccount(Context context){
initView(context);
}
private void initView(Context context){
mContext = context;
ftpUtil = new FtpUtils();
mContext = context;
inflaterView = LayoutInflater.from(context).inflate(R.layout.account_layout, null);
mEdtFTPDialogAddress = (EditText)inflaterView.findViewById(R.id.edtFTPaddress);
mEdtFTPDialogPort = (EditText)inflaterView.findViewById(R.id.edtFtpDialogProt);
mEdtFTPDialogUserName = (EditText)inflaterView.findViewById(R.id.edtFTPUserName);
mEdtFTPDialogPWD = (EditText)inflaterView.findViewById(R.id.edtFTPPassword);
mBtnDialogOK = (Button)inflaterView.findViewById(R.id.btnFTPDilaogOK);
mBtnDialogOK.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if(!ftpUtil.netWorkAvaliable(mContext)){
Toast.makeText(mContext, "net isn't working.", Toast.LENGTH_SHORT).show();
return ;
}else{
new ConnectClientTask().execute(new String[]{mEdtFTPDialogAddress.getText().toString(),mEdtFTPDialogUserName.getText().toString(),
mEdtFTPDialogPWD.getText().toString()});
}
}
});
initData();
}
private void initData(){
mEdtFTPDialogAddress.setText("192.168.1.186");
mEdtFTPDialogPort.setText("21");
mEdtFTPDialogUserName.setText("ftpCount");
mEdtFTPDialogPWD.setText("111");
}
public View getView(){
return this.inflaterView;
}
private class ConnectClientTask extends AsyncTask<String, String, String>{
private ProgressDialog pgdialog;
private boolean isSuccess = false;
@Override
protected void onPreExecute() {
super.onPreExecute();
pgdialog = new ProgressDialog(mContext);
pgdialog.setMessage("Please wait while loading...");
pgdialog.setIndeterminate(true);
pgdialog.setCancelable(false);
pgdialog.show();
}
@Override
protected String doInBackground(String... params) {
/*
for(String str:params){
Log.e(tag, str);
}*/
isSuccess = FtpFileManage.getInstance().connectClient(params);
return null;
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if(isSuccess){
Log.d(tag, "ConnectClientTask isSuccess");
Intent intent = new Intent(mContext,FtpBrowserActivity2.class);
mContext.startActivity(intent);
}else{
Log.e(tag, "ConnectClientTask failed");
Toast.makeText(mContext, "connect failed.", Toast.LENGTH_SHORT).show();
}
pgdialog.dismiss();
}
}
public class FtpInfo{
//model
private int id;
private String clientType;
private String address;
private int port;
private String userName;
private String pwd;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getClientType() {
return clientType;
}
public void setClientType(String clientType) {
this.clientType = clientType;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
}
}
FtpBrowserActivity2.java
package com.ftpbrowser.sample;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.net.ftp.FTPFile;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.Toast;
public class FtpBrowserActivity2 extends Activity implements OnItemClickListener{
public static final int REFRESH_DATA=1;
public static final int STARTLIST_DATA=2;
public static final int EMPTY_DATA=-1;
public static FtpBrowserActivity2 browserActivity;
private ListView fileListView;
private FileAdapter adapter;
private List<Map<String, Object>> items;
final static String STORE_DIRECTORY=Environment.getExternalStorageDirectory().getAbsolutePath();
FtpFileManage ma;
List<FtpFileInfo> Infofiles;
boolean firstStart=true;
Handler mHandler=new Handler(){
@Override
public void handleMessage(android.os.Message msg) {
switch(msg.what){
case STARTLIST_DATA:
ma.startListPath();
break;
case REFRESH_DATA:
listDir(false);
break;
case EMPTY_DATA:
Toast.makeText(browserActivity, msg.obj.toString(), 200).show();
break;
}
};
};
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTitle(" ");
View v=LayoutInflater.from(this).inflate(R.layout.main, null);
setContentView(v);
registerForContextMenu(v);
FtpBrowserActivity2.browserActivity=this;
fileListView = (ListView) findViewById(R.id.ftpFilelist);
ma=FtpFileManage.getInstance();
ma.setActivity();
// new ConnectFtpServer().start();
}
class ConnectFtpServer extends Thread{
@Override
public void run() {
// boolean success=ma.connectClient(new String[]{"192.168.1.186","ftpCount", "111"});
boolean success=ma.connectClient(new String[]{"192.168.1.186","ftpServer", "11"});
if(success){
mHandler.sendEmptyMessageDelayed(STARTLIST_DATA, 1000);
}else{
Message m=mHandler.obtainMessage(EMPTY_DATA, "please check ftp server normal");
m.sendToTarget();
}
}
}
private List<Map<String, Object>> bindList(){
List<Map<String, Object>> list= new ArrayList<Map<String, Object>>();
Infofiles=ma.getlistFilesInfo();
for (FtpFileInfo file : Infofiles){
Map<String, Object> map = new HashMap<String, Object>();
if(file.isDirectory()){
map.put(FileAdapter.FILE_IMAGE, R.drawable.directory);
}else{
map.put(FileAdapter.FILE_IMAGE, R.drawable.file_doc);
}
map.put(FileAdapter.FILE_NAME, file.getFileName());
map.put(FileAdapter.FILE_PATH, file.getFilePath());
map.put(FileAdapter.FTP_FILE_INFO, file);
list.add(map);
}
return list;
}
private void listDir(boolean choose){
items=bindList();
adapter = new FileAdapter(getApplicationContext(), items,choose);
adapter.setFile_type(FileType.FTP_FILE_TYPE);
fileListView.setAdapter(adapter);
fileListView.setOnItemClickListener(this);
fileListView.setOnItemLongClickListener(new ChooseDialog());
fileListView.setSelection(0);
}
@Override
protected void onResume() {
if(firstStart){
firstStart=false;
mHandler.sendEmptyMessageDelayed(STARTLIST_DATA, 1000);
}
super.onResume();
}
private boolean isMove=false;
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
return super.onPrepareOptionsMenu(menu);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(0, Menu.FIRST, 0, "choose file");
menu.add(1, Menu.FIRST+1, 0, "upload file");
menu.add(1, Menu.FIRST+2, 0, "download file");
menu.add(2, Menu.FIRST+3, 0, "move file");
menu.add(2, Menu.FIRST+4, 0, "copy file");
menu.add(3, Menu.FIRST+5, 0, "delete file");
menu.add(3, Menu.FIRST+6, 0, "paste file");
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
Intent i=new Intent(this,LoacalFileActivity.class);
switch(item.getItemId()){
case Menu.FIRST:
listDir(true);
break;
case Menu.FIRST+1:
startActivityForResult(i, 0);
break;
case Menu.FIRST+2:
ma.downLoadFile(STORE_DIRECTORY+File.separator+"temp");
break;
case Menu.FIRST+3:
isMove=ma.move();
break;
case Menu.FIRST+4:
isMove=ma.copy();
break;
case Menu.FIRST+5:
ma.deleteFile();
break;
case Menu.FIRST+6:
ma.paste(isMove);
break;
}
return super.onOptionsItemSelected(item);
}
int pastePos=0;
String oldDir="";
@Override
public void onCreateContextMenu(ContextMenu menu, View v,ContextMenuInfo menuInfo) {
menu.add(0, Menu.FIRST, 0, "paste");
super.onCreateContextMenu(menu, v, menuInfo);
}
@Override
public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId()) {
case 1:
ma.moveOneFile(pastePos, oldDir);
break;
}
return super.onContextItemSelected(item);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch(resultCode){
case 11:
ArrayList<String> filesPath=(ArrayList<String>)FileInfo.upFilePath;
if(filesPath!=null&&filesPath.size()>0){
ma.uploadFile(filesPath);
Toast.makeText(getApplicationContext(), "upload local file......", 200).show();
}else{
Toast.makeText(getApplicationContext(), "upload file fail", 200).show();
}
break;
}
super.onActivityResult(requestCode, resultCode, data);
}
public FileAdapter getFileAdapter(){
return adapter;
}
@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
if(keyCode == KeyEvent.KEYCODE_BACK){
return ma.onKeyUp(keyCode, event);
}
else{
return super.onKeyUp(keyCode, event);
}
}
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
ma.onItemClickListener(arg2);
FTPFile ftpFile = Infofiles.get(arg2).getFtpFile();
if (ftpFile.isDirectory()){
// listDir();
}
else{
Toast.makeText(this,"no directry",Toast.LENGTH_SHORT).show();
}
}
class ChooseDialog implements android.widget.AdapterView.OnItemLongClickListener{
@Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
AlertDialog.Builder builder=new AlertDialog.Builder(browserActivity);
String[] items={"rename file","delete file","move file","copy file"};
builder.setItems(items, new LongDialog(arg2));
builder.create().show();
return true;
}
}
/**
*
* @author Administrator
*
*/
class LongDialog implements DialogInterface.OnClickListener{
private int pos=0;
public LongDialog(int pos){
this.pos=pos;
}
@Override
public void onClick(DialogInterface dialog, int which) {
switch(which){
case 0:
ChooseDialog(0,pos);
break;
case 1:
ChooseDialog(1,pos);
break;
case 2:
ChooseDialog(2,pos);
break;
case 3:
break;
}
}
}
/**
*
* @param id
*/
private void ChooseDialog(final int id,final int pos){
AlertDialog.Builder builder=new AlertDialog.Builder(this);
switch(id){
case 0:
ma.showFileRenameDialog(Infofiles.get(pos));
break;
case 1:
builder.setTitle(" ?");
builder.setPositiveButton(" ", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
ma.deleteOneFile(pos);
}
});
builder.setNegativeButton(" ",null);
break;
case 2:
builder.setTitle(" ?");
builder.setPositiveButton(" ", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
oldDir=ma.oldMovePathBefore();
}
});
builder.setNegativeButton(" ",null);
break;
case 3:
builder.setTitle(" ?");
builder.setPositiveButton(" ", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
builder.setNegativeButton(" ",null);
break;
}
builder.create().show();
}
}
以上のコードは十分に研究を学んで、サーバーは自分で探して、すでにアップロードしました
http://download.csdn.net/detail/yudajun/5140876
分からないことがあれば、伝言を残して交流してください.
2014/4/25更新、詳細コードアップロード
クリックしてリンクを開く