Android|Android xUtils3 文件下载

基于xUtils3实现单个文件,由于官方sample的文件下载实现较为复杂,所以本文简单实现了文件下载功能。


1、集成xUtils3,采用gradle方式

compile 'org.xutils:xutils:3.3.4'



2、权限





3、初始化,这个类要在AndroidManifest.xml文件节点下配置


public class BaseApplication extends Application {@Override public void onCreate() { super.onCreate(); x.Ext.init(this); }}


4、下载实现


public class MainActivity extends AppCompatActivity {private static final String BASE_URL = "http://192.168.155.4:8080"; private static final String BASE_PATH = Environment.getExternalStorageDirectory().getPath() + File.separator; private Button buttonDownloadFile; private ProgressDialog progressDialog; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); buttonDownloadFile = (Button) findViewById(R.id.bt_downloadFile); buttonDownloadFile.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String url = BASE_URL + "/code.rar"; String path = BASE_PATH + "code.rar"; downloadFile(url, path); } }); }private void downloadFile(final String url, String path) { progressDialog = new ProgressDialog(this); RequestParams requestParams = new RequestParams(url); requestParams.setSaveFilePath(path); x.http().get(requestParams, new Callback.ProgressCallback() { @Override public void onWaiting() { }@Override public void onStarted() { }@Override public void onLoading(long total, long current, boolean isDownloading) { progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); progressDialog.setMessage("亲,努力下载中。。。"); progressDialog.show(); progressDialog.setMax((int) total); progressDialog.setProgress((int) current); }@Override public void onSuccess(File result) { Toast.makeText(MainActivity.this, "下载成功", Toast.LENGTH_SHORT).show(); progressDialog.dismiss(); }@Override public void onError(Throwable ex, boolean isOnCallback) { ex.printStackTrace(); Toast.makeText(MainActivity.this, "下载失败,请检查网络和SD卡", Toast.LENGTH_SHORT).show(); progressDialog.dismiss(); }@Override public void onCancelled(CancelledException cex) { }@Override public void onFinished() { } }); } }


5、布局文件



6、运行截图



7、源码下载地址

源码CSDN下载


【Android|Android xUtils3 文件下载】

    推荐阅读