现在的位置: 首页 > 综合 > 正文

Android实现文件上传下载【xUtils工具实现】

2017年03月28日 ⁄ 综合 ⁄ 共 2265字 ⁄ 字号 评论关闭

在github中用利用xUtils工具实现Android的文件上传下载。

xUtils简介与使用:https://github.com/dundunhuihui/xUtils-1

在该处可以下载相应的jar包。

下面主要实现文件的下载:去github官网上看xUtils使用起来非常简单。

细节详解:1)handler.cancel();这段代码在官网上写的有,就是在文件下载完成后自动关闭,但是bug问题是:xUtils底层启动的三个子线程,当线程还没执行完的时候,该方法已经开始执行,导致下载文件总是失败。所以应该屏蔽该代码。

public class MainActivity extends Activity {
	private EditText et_path;
	private TextView tv_info;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
	    et_path=(EditText)findViewById(R.id.et_path);
	    tv_info=(TextView)findViewById(R.id.tv_info);
	}
	
	public void download(View view){
		String path=et_path.getText().toString().trim();
		if(TextUtils.isEmpty(path)){
			Toast.makeText(this, "请输入正确的下载路径", 0).show();
			return;
		}else{
			Toast.makeText(this, "下载路径正确,马上进行下载!", 0).show();
			HttpUtils http = new HttpUtils();
			HttpHandler handler = http.download(path,
					"/sdcard/xxx.zip",
			    true, // 如果目标文件存在,接着未完成的部分继续下载。服务器不支持RANGE时将从新下载。
			    true, // 如果从请求返回信息中获取到文件名,下载完成后自动重命名。
			    new RequestCallBack<File>() {

			        @Override
			        public void onStart() {
			        	tv_info.setText("conn...");
			        }

			        @Override
			        public void onLoading(long total, long current, boolean isUploading) {
			        	tv_info.setText(current + "/" + total);
			        }

			        @Override
			        public void onSuccess(ResponseInfo<File> responseInfo) {
			        	tv_info.setText("downloaded:" + responseInfo.result.getPath());
			        }


			        @Override
			        public void onFailure(HttpException error, String msg) {
			        	tv_info.setText(msg);
			        }
			});

			//调用cancel()方法停止下载
			<strong><span style="color:#cc0000;">//handler.cancel();</span></strong>
			
		}
	}

 
}

xml配置文件:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.example.kaiyuan.MainActivity" >

    <EditText
        android:id="@+id/et_path"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="http://10.0.2.2:8080/Thread/temp.exe" />

    <Button
        android:onClick="download"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="下载"/>

    <TextView
        android:id="@+id/tv_info"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        />
    
</LinearLayout>

需要的权限:

 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.INTERNET"/>

演示效果:

                 

   

抱歉!评论已关闭.