Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Android開發筆記(一百一十)使用http框架上傳文件

Android開發筆記(一百一十)使用http框架上傳文件

編輯:關於Android編程

HTTP上傳

與文件下載相比,文件上傳的場合不是很多,通常用於上傳用戶頭像、朋友圈發布圖片/視頻動態等等,而且上傳文件需要服務器配合,所以容易被app開發者忽略。就上傳的形式來說,app一般采用http上傳文件,很少用ftp上傳文件。

HttpURLConnection上傳

很可惜Android沒有提供專門的文件上傳工具類,所以我們要自己寫代碼實現上傳功能了。其實也不難,一樣是按照普通網絡訪問的POST流程,只是要采用“multipart/form-data”方式來分段傳輸。另外文件上傳需要運用打開文件的對話框。


下面是HttpURLConnection上傳文件的工具類代碼:
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class UploadUtil {
	private static final String TAG = "UploadUtil";
	
	public static String upload(String uploadUrl, String uploadFile) {
		String fileName = "";
		int pos = uploadFile.lastIndexOf("/");
		if (pos >= 0) {
			fileName = uploadFile.substring(pos + 1);
		}
		
		String end = "\r\n";
		String Hyphens = "--";
		String boundary = "WUm4580jbtwfJhNp7zi1djFEO3wNNm";
		try {
			URL url = new URL(uploadUrl);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setDoInput(true);
			conn.setDoOutput(true);
			conn.setUseCaches(false);
			conn.setRequestMethod("POST");
			conn.setRequestProperty("Connection", "Keep-Alive");
			conn.setRequestProperty("Charset", "UTF-8");
			conn.setRequestProperty("Content-Type",
					"multipart/form-data;boundary=" + boundary);

			DataOutputStream ds = new DataOutputStream(conn.getOutputStream());
			ds.writeBytes(Hyphens + boundary + end);
			ds.writeBytes("Content-Disposition: form-data; "
					+ "name=\"file1\";filename=\"" + fileName + "\"" + end);
			ds.writeBytes(end);
			FileInputStream fStream = new FileInputStream(uploadFile);
			// 每次寫入1024字節
			int bufferSize = 1024;
			byte[] buffer = new byte[bufferSize];
			int length = -1;
			// 將文件數據寫入到緩沖區
			while((length = fStream.read(buffer)) != -1) { 
				ds.write(buffer, 0, length);
			}
			ds.writeBytes(end);
			ds.writeBytes(Hyphens + boundary + Hyphens + end);
			fStream.close();
			ds.flush();
			// 獲取返回內容
			InputStream is = conn.getInputStream();
			int ch;
			StringBuffer b = new StringBuffer();
			while ((ch = is.read()) != -1) {
				b.append((char) ch);
			}
			ds.close();
			return "SUCC";
		} catch (Exception e) {
			e.printStackTrace();
			return "上傳失敗:" + e.getMessage();
		}
	}
}


android-async-http上傳

HttpURLConnection需要開發者自己拼接請求包,容易出錯,並且處理單一不夠靈活,因此湧現了幾個開源的http框架,方便開發者進行http通信的編碼。android-async-http是這其中使用較多的一個網絡請求框架,它的項目地址在 https://github.com/loopj/android-async-http 。


據官方介紹,android-async-http是基於Apache HttpClient庫之上的一個異步網絡請求處理庫,網絡處理均基於Android的非UI線程,通過回調方法處理請求結果。這裡我們使用該庫進行文件上傳,主要用到AsyncHttpClient類的post方法,要上傳的文件信息放在RequestParams對象中。


下面是android-async-http上傳文件的工具類代碼:
import java.io.File;

import com.example.exmupload.MainActivity;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.RequestParams;

import android.util.Log;

public class AsyncUtil {
    private static final String TAG = "AsyncUtil";
	
	public static String upload(final MainActivity act, String uploadServlet, String filePath, boolean isBinary) {
		try {
			//服務端的commons-fileupload只支持multipart/form-data方式
			//application/octet-stream表示任意的二進制文件,包括圖片、音頻、視頻、壓縮文件等等
			String contentType = "application/octet-stream";
			//String contentType = "multipart/form-data";
			RequestParams params = new RequestParams();
			if (isBinary == true) {
				params.put("file", new File(filePath), contentType);
			} else {
				params.put("file", new File(filePath));
			}
			Log.d(TAG, "contentType="+contentType);
			AsyncHttpClient client = new AsyncHttpClient();
			//AsyncHttpResponseHandle不在ui線程運行,不能直接操作ui
			//如果在此處定義AsyncHttpResponseHandle對象,則運行報錯:
			//java.lang.IllegalArgumentException: Synchronous ResponseHandler used in AsyncHttpClient. You should create your response handler in a looper thread or use SyncHttpClient instead.
			client.post(uploadServlet, params, act.mAsyncHandler);
			return "uploadByFile";
		} catch (Exception e) {
			e.printStackTrace();
			return e.getMessage();
		}
	}

//	//下面代碼在MainActivity.java中定義
//	public AsyncHttpResponseHandler mAsyncHandler = new AsyncHttpResponseHandler() {
//		@Override
//		public void onSuccess(int status, Header[] headers, byte[] data) {
//			String result = "文件上傳成功!";
//			Message msg = Message.obtain();
//			msg.what = ASYNC;
//			msg.obj = result;
//			mHandler.sendMessage(msg);
//		}
//
//		@Override
//		public void onFailure(int status, Header[] headers, byte[] data, Throwable e) {
//			String result = "文件上傳失敗!"+e.getMessage();
//			Message msg = Message.obtain();
//			msg.what = ASYNC;
//			msg.obj = result;
//			mHandler.sendMessage(msg);
//		}
//	};
	
}


Retrofit上傳

Retrofit是網絡請求框架中的後起之秀,它的項目地址在 https://github.com/square/retrofit 。據官方介紹,Retrofit是一個類型安全的REST客戶端,用於Android平台。Retrofit基於注解方式,提供了JSON to POJO(Plain Ordinary Java Object,簡單Java對象)、POJO to JSON、網絡請求(POST/GET/PUT/DELETE)等通信行為的封裝。


Retrofit依賴okhttp庫,早期的版本用的是okhttp2(如okhttp-2.5.0.jar),最新的版本如retrofit-2.1.0.jar用的是okhttp3(如okhttp-3.3.1.jar),所以工程引用Retrofit庫時,要注意導入正確的okhttp庫。這裡我們通過文件上傳來演示Retrofit的使用方法,因為采用了注解方式,所以不太方便文字說明,還是直接上代碼好了。


下面是Retrofit上傳文件的工具類代碼:
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import com.example.exmupload.MainActivity;

import okhttp3.MediaType;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.http.Multipart;
import retrofit2.http.PartMap;
import retrofit2.http.POST;

import android.util.Log;
import android.webkit.MimeTypeMap;

public class RetrofitUtil {
	private static final String TAG = "RetrofitUtil";
	
	public interface ApiInterface {
		//這裡的POST是不帶ip也不帶域名的地址,下面uploadHost才帶ip/域名和端口,如http://192.168.0.212:8080/
		@Multipart
		@POST("UploadTest/uploadServlet")
		Call upload(@PartMap Map params);
	}
	
	public static void upload(final MainActivity act, String uploadHost, String filePath) {
		File file1 = new File(filePath);
		Retrofit retrofit = new Retrofit.Builder().baseUrl(uploadHost).build();
		ApiInterface apiService = retrofit.create(ApiInterface.class);
		// 獲取文件真實的內容類型
//		String mimeType = MimeTypeMap.getSingleton()
//				.getMimeTypeFromExtension(MimeTypeMap.getFileExtensionFromUrl(file1.getPath()));
//		RequestBody fileBody = RequestBody.create(MediaType.parse(mimeType), filePath);
		RequestBody fileBody = RequestBody.create(MediaType.parse("multipart/form-data"), filePath);
		Map params = new HashMap<>();
		// 如果要上傳多個文件,可對該Map對象進行put操作
		params.put("file\"; filename=\"" + file1.getName() + "", fileBody);
		Call call = apiService.upload(params);
		call.enqueue(new Callback() {
			@Override
			public void onResponse(Call call, Response response) {
				try {
					String jsonString = new String(response.body().bytes()); // 這就是返回的json字符串了。
					Log.d(TAG, "onResponse succ : "+jsonString);
					act.notify(act.RETROFIT, "onResponse succ "+jsonString);
				} catch (IOException e) {
					e.printStackTrace();
					act.notify(act.RETROFIT, "onResponse "+e.getMessage());
				}
			}

			@Override
			public void onFailure(Call call, Throwable throwable) {
				Log.d(TAG, "onFailure : "+throwable.getMessage());
				act.notify(act.RETROFIT, "onFailure "+throwable.getMessage());
			}
		});
	}
	
}


服務器接收文件

commons-fileupload

文件上傳需要服務器配合,服務端若用java編碼,則可通過commons-fileupload來接收文件。commons-fileupload是個通用的各類網絡協議通信包,包括ftp/telnet/smtp/pop3等協議。該包依賴於commons-io庫,它們的下載地址如下:
commons-fileupload-1.2.1.jar https://mirrors.tuna.tsinghua.edu.cn/apache/commons/fileupload/binaries/
commons-io-1.4.jar https://mirrors.tuna.tsinghua.edu.cn/apache/commons/io/binaries/


下面是服務端采用commons-fileupload接收文件的代碼例子:
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.Writer;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.util.Streams;

public class UploadServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    public UploadServlet() {
        super();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.doPost(request, response);
	}

	@SuppressWarnings("unchecked")
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		System.out.println("request.getContentType()="+request.getContentType());
		response.setContentType("text/html");
        response.setCharacterEncoding("UTF-8");
        Writer o = response.getWriter();
		
		//首先判斷Content-Type是不是multipart/form-data。同時也判斷了form的提交方式是不是post
		if (ServletFileUpload.isMultipartContent(request)) {
			request.setCharacterEncoding("utf-8");
			// 實例化一個硬盤文件工廠,用來配置上傳組件ServletFileUpload   
			DiskFileItemFactory factory =  new DiskFileItemFactory();
			//設置文件存放的臨時文件夾,這個文件夾要真實存在
			File fileDir = new File("../webapps/");
			if (fileDir.isDirectory() && fileDir.exists()==false) {
				fileDir.mkdir();
			}
			factory.setRepository(fileDir);
			
			//設置最大占用的內存
			factory.setSizeThreshold(1024000);
			//創建ServletFileUpload對象
			ServletFileUpload sfu = new ServletFileUpload(factory);
			sfu.setHeaderEncoding("utf-8");
			//設置單個文件最大值byte 
			sfu.setFileSizeMax(102400000);
			//所有上傳文件的總和最大值byte   
			sfu.setSizeMax(204800000);
			
			List items =  null;
			try {
				items = sfu.parseRequest(request);
	    		System.out.println("items.size()="+items.size());
            } catch(Exception e) {   
                e.printStackTrace();   
            }
            
            Iterator iter = items==null?null:items.iterator();
            //文件上傳後存放的路徑目錄
            File dir = new File("D:/");
			if (dir.exists()==false) {
				dir.mkdirs();
			}  
            while (iter!=null && iter.hasNext()) {
            	FileItem item = (FileItem) iter.next();
            	if (item.isFormField()) { //如果傳過來的是普通的表單域
            		System.out.print("普通的表單域:");   
                    System.out.print(new String(item.getFieldName()) + "  ");   
                    System.out.println(new String(item.getString("UTF-8")));   
            	} else if (!item.isFormField()) { //文件域
            		System.out.println("源文件:" + item.getName());
            		String fileName = item.getName();
            		if (fileName.indexOf("\\") >= 0) {
            			fileName = item.getName().substring(item.getName().lastIndexOf("\\"));
            		}
            		BufferedInputStream in = new BufferedInputStream(item.getInputStream());
                    BufferedOutputStream out = new BufferedOutputStream(
                            new FileOutputStream(new File(dir.getAbsolutePath()+ fileName))); 
                    Streams.copy(in, out, true);
                    o.write("文件上傳成功");
            	}
            }
		} else {
            System.out.println("表單的Content-Type錯誤");
        } 
	}

}


FTP上傳

普通FTP

在從前帶寬有限的互聯網時代,FTP共享影視資源曾經盛行一時,如今寬帶普及了,特別是步入移動互聯網時代,FTP用的便越來越少了。不管怎樣,作為一個技術手段,我們還是溫習一下FTP上傳文件的用法,java上可導入commons-net-3.3.jar,該庫是集成了常見的網絡通訊協議,包括但不限於:ftp、telnet、smtp、pop3等等。


commons-net進行FTP上傳用的是FTPClient類,下面是FTPClient上傳文件的工具類代碼:
import java.io.FileInputStream;
import java.io.IOException;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;

public class FTPUtil {
	private static String mUurl;
	private static String mPort;
	private static String mUsername;
	private static String mPassword;
	
	public static void setUser(String url, String port, String username, String password) {
		mUurl = url;
		mPort = port;
		mUsername = username;
		mPassword = password;
	}
	
	public static String upload(String remotePath, String filePath, String fileName) {
		FTPClient ftpClient = new FTPClient();
		String result = "SUCC";
		try {
			ftpClient.connect(mUurl, Integer.parseInt(mPort));
			boolean loginResult = ftpClient.login(mUsername, mPassword);
			int returnCode = ftpClient.getReplyCode();
			if (loginResult && FTPReply.isPositiveCompletion(returnCode)) { //登錄成功
				ftpClient.makeDirectory(remotePath);
				// 設置上傳目錄
				ftpClient.changeWorkingDirectory(remotePath);
				ftpClient.setBufferSize(1024);
				ftpClient.setControlEncoding("UTF-8");
				ftpClient.enterLocalPassiveMode();
				FileInputStream fis = new FileInputStream(filePath + fileName);
				ftpClient.storeFile(fileName, fis);
			} else { //登錄失敗
				result = "FAIL";
			}
		} catch (IOException e) {
			e.printStackTrace();
			result = "FTP客戶端出錯!" + e.getMessage();
		} finally {
			try {
				ftpClient.disconnect();
			} catch (IOException e) {
				e.printStackTrace();
				result = "關閉FTP連接發生異常!" + e.getMessage();
			}
		}
		return result;
	}
}


安全的SFTP

SFTP是Secure FTP的簡稱,顧名思義它比FTP要安全。不過對於普通用戶來說,SFTP用得比FTP還少,就不啰嗦了。


調用SFTP可導入JSch庫,最新的jar包是jsch-0.1.53.jar,該庫操作SFTP主要用ChannelSftp類,下面是JSch上傳文件的工具類代碼:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Properties;
import java.util.Vector;

import android.util.Log;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.ChannelSftp.LsEntry;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpException;

public class SFTPUtil {
	private static final String TAG = "SFTPUtil";
	public static int SUCC = 0;
	public static int FAIL = -1;

	//連接sftp服務器
	public static ChannelSftp connect(String host, int port, String username, String password) {
		ChannelSftp sftp = null;
		try {
			JSch jsch = new JSch();
			jsch.getSession(username, host, port);
			Session session = jsch.getSession(username, host, port);
			session.setPassword(password);
			Properties config = new Properties();
			config.put("StrictHostKeyChecking", "no");
			session.setConfig(config);
			session.connect();
			Channel channel = session.openChannel("sftp");
			channel.connect();
			sftp = (ChannelSftp) channel;
			Log.d(TAG, "Connected to " + host + ".");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return sftp;
	}

	//上傳文件
	public static String upload(ChannelSftp sftp, String directory, String uploadFile) {
		try {
			sftp.cd(directory);
			File file = new File(uploadFile);
			sftp.put(new FileInputStream(file), file.getName());
			Log.d(TAG, "Upload succ. " + uploadFile);
			return "SUCC";
		} catch (Exception e) {
			e.printStackTrace();
			return e.getMessage();
		}
	}

	//下載文件
	public static int download(ChannelSftp sftp, String directory, String downloadFile, String saveFile) {
		try {
			sftp.cd(directory);
			File file = new File(saveFile);
			sftp.get(downloadFile, new FileOutputStream(file));
			Log.d(TAG, "Download succ. " + downloadFile);
			return SUCC;
		} catch (Exception e) {
			e.printStackTrace();
			return FAIL;
		}
	}

	//刪除文件
	public static int delete(ChannelSftp sftp, String directory, String deleteFile) {
		try {
			sftp.cd(directory);
			sftp.rm(deleteFile);
			Log.d(TAG, "Delete succ. " + deleteFile);
			return SUCC;
		} catch (Exception e) {
			e.printStackTrace();
			return FAIL;
		}
	}

	//列出目錄下的文件
	public static Vector listFiles(ChannelSftp sftp, String directory) throws SftpException {
		//Vector容器內部保存的是LsEntry類型對象。
		return sftp.ls(directory);
	}

}


下面是文件上傳(包括http上傳和ftp上傳)的頁面代碼例子:
import java.util.Map;

import org.apache.http.Header;

import com.aqi00.lib.dialog.FileSelectFragment;
import com.aqi00.lib.dialog.FileSelectFragment.FileSelectCallbacks;
import com.example.exmupload.util.AsyncUtil;
import com.example.exmupload.util.FTPUtil;
import com.example.exmupload.util.RetrofitUtil;
import com.example.exmupload.util.SFTPUtil;
import com.example.exmupload.util.UploadUtil;
import com.jcraft.jsch.ChannelSftp;
import com.loopj.android.http.AsyncHttpResponseHandler;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity implements OnClickListener,FileSelectCallbacks {
	
    private static final String TAG = "MainActivity";
    private static TextView tv_filename;
    private Button btn_select;
    private Button btn_upload;
    private Button btn_async;
    private Button btn_retrofit;
    private Button btn_ftp;
    private Button btn_sftp;
    private static TextView tv_result;
    public static String mUploadHost = "http://192.168.0.212:8080/";
    public static String mUploadService = "UploadTest/uploadServlet";
    private String mServletUrl = mUploadHost + mUploadService;
    
    @Override  
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        tv_filename = (TextView) findViewById(R.id.tv_filename);
        btn_select = (Button) findViewById(R.id.btn_select);
        btn_upload = (Button) findViewById(R.id.btn_upload);
        btn_async = (Button) findViewById(R.id.btn_async);
        btn_retrofit = (Button) findViewById(R.id.btn_retrofit);
        btn_ftp = (Button) findViewById(R.id.btn_ftp);
        btn_sftp = (Button) findViewById(R.id.btn_sftp);
        tv_result = (TextView) findViewById(R.id.tv_result);
        
        btn_select.setOnClickListener(this);
        btn_upload.setOnClickListener(this);
        btn_async.setOnClickListener(this);
        btn_retrofit.setOnClickListener(this);
        btn_ftp.setOnClickListener(this);
        btn_sftp.setOnClickListener(this);
    }
    
	@Override
	public void onClick(View v) {
		String file_path = tv_filename.getText().toString().trim();
		if (v.getId() == R.id.btn_select) {
			FileSelectFragment.show(this, new String[]{"jpg","png","gif","txt"}, null);
			return;
		}
		if (file_path.length() <= 0) {
			Toast.makeText(this, "請選擇要上傳的文件", Toast.LENGTH_LONG).show();
			return;
		}
		if (v.getId() == R.id.btn_upload) {
			tv_result.setText("開始HttpURLConnection上傳");
			new ConnnectionThread(file_path).start();
		} else if (v.getId() == R.id.btn_async) {
			tv_result.setText("開始async上傳");
			new AsyncThread(file_path).start();
		} else if (v.getId() == R.id.btn_retrofit) {
			tv_result.setText("開始retrofit上傳");
			new RetrofitThread(file_path).start();
		} else if (v.getId() == R.id.btn_ftp) {
			new FTPThread(file_path).start();
		} else if (v.getId() == R.id.btn_sftp) {
			new SFTPThread(file_path).start();
		}
	}

	public void notify(int type, String message) {
		Message msg = Message.obtain();
		msg.what = type;
		msg.obj = message;
		mHandler.sendMessage(msg);
	}

	private class ConnnectionThread extends Thread {
		private String mFilePath;
		public ConnnectionThread(String file_path) {
			mFilePath = file_path;
		}
		
		@Override
		public void run() {
			String result = UploadUtil.upload(mServletUrl, mFilePath);
			MainActivity.this.notify(COMMON, "upload :" + result);
		}
	}
	
	private class AsyncThread extends Thread {
		private String mFilePath;
		public AsyncThread(String file_path) {
			mFilePath = file_path;
		}
		
		@Override
		public void run() {
			String result = AsyncUtil.upload(MainActivity.this, mServletUrl, mFilePath, true);
			MainActivity.this.notify(ASYNC, "upload :" + result);
		}
	}
	
	public AsyncHttpResponseHandler mAsyncHandler = new AsyncHttpResponseHandler() {
		@Override
		public void onSuccess(int status, Header[] headers, byte[] data) {
			MainActivity.this.notify(ASYNC, "文件上傳成功!");
		}

		@Override
		public void onFailure(int status, Header[] headers, byte[] data, Throwable e) {
			MainActivity.this.notify(ASYNC, "文件上傳失敗!"+e.getMessage());
		}
	};
	
	private class RetrofitThread extends Thread {
		private String mFilePath;
		public RetrofitThread(String file_path) {
			mFilePath = file_path;
		}
		
		@Override
		public void run() {
			RetrofitUtil.upload(MainActivity.this, mUploadHost, mFilePath);
		}
	}
	
	private class FTPThread extends Thread {
		private String mFilePath;
		public FTPThread(String file_path) {
			mFilePath = file_path;
		}
		
		@Override
		public void run() {
			String filepath = mFilePath.substring(0, mFilePath.lastIndexOf("/")+1);
			String filename = mFilePath.substring(mFilePath.lastIndexOf("/")+1);
			FTPUtil.setUser("172.16.16.146", "21", "testftp", "testftp");
			String result = FTPUtil.upload("/home/testftp", filepath, filename);
			MainActivity.this.notify(FTP, result);
		}
	}

	private class SFTPThread extends Thread {
		private String mFilePath;
		public SFTPThread(String file_path) {
			mFilePath = file_path;
		}
		
		@Override
		public void run() {
			ChannelSftp sftp = SFTPUtil.connect("172.16.16.133", 22, "oracle", "oracle");
			String result = SFTPUtil.upload(sftp, "/home/oracle", mFilePath);
			MainActivity.this.notify(SFTP, result);
		}
	}

	public int COMMON = 0;
	public int ASYNC = 1;
	public int RETROFIT = 2;
	public int FTP = 3;
	public int SFTP = 4;
	@SuppressLint("HandlerLeak")
	public Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			String result = (String) msg.obj;
			if (msg.what == COMMON) {
				tv_result.setText(tv_result.getText().toString()+"\n"+result);
			} else if (msg.what == ASYNC) {
				tv_result.setText(tv_result.getText().toString()+"\n"+result);
			} else if (msg.what == RETROFIT) {
				tv_result.setText(tv_result.getText().toString()+"\n"+result);
			} else if (msg.what == FTP) {
				showTip("FTP文件上傳結果:"+result);
			} else if (msg.what == SFTP) {
				showTip("sftp文件上傳結果:"+result);
			}
		}
	};
	
	private void showTip(String desc) {
		Toast.makeText(getApplicationContext(), desc, Toast.LENGTH_SHORT).show();
	}
	
	@Override
	public void onConfirmSelect(String absolutePath, String fileName,
			Map map_param) {
		String path = absolutePath + "/" + fileName;
		tv_filename.setText(path);
	}

	@Override
	public boolean isFileValid(String absolutePath, String fileName,
			Map map_param) {
		return true;
	}

}
  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved