android下载图片和视频到本地,求代码,求案例
发布网友
发布时间:2022-07-23 10:28
我来回答
共1个回答
热心网友
时间:2023-11-30 11:13
下面是android多线程下载例子截图:
package mm.shandong.com.testmultithreaddownload;
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import java.io.File;
import mm.shandong.com.testmultithreaddownload.thread.UpdateUIThread;
import mm.shandong.com.testmultithreaddownload.util.FileUtil;
public class TestMultiThreadDownLoadActivity extends AppCompatActivity {
ProgressDialog pb;
EditText editText;
Handler handler;
private UpdateUIThread mUpdateUIThread = null;
///文件路径
private String url =
"http://gdown.baidu.com/data/wisegame/3c00add7144d3915/kugouyinle.apk";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test_multi_thread_down_load);
editText = (EditText) findViewById(R.id.editText);
initHandler();
}
public void initHandler() {
handler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case FileUtil.startDownloadMeg:
pb.setMax(mUpdateUIThread.getFileSize()); //开始
break;
case FileUtil.updateDownloadMeg:
if (!mUpdateUIThread.isCompleted()) //下载进度消息
{
pb.setProgress(mUpdateUIThread.getDownloadSize());
pb.setMessage("下载速度:" +
mUpdateUIThread.getDownloadSpeed() + "k/秒 " +
" 下载百分比" + mUpdateUIThread.getDownloadPercent() + "%");
} else {
pb.setMessage("下载完成");
}
break;
case FileUtil.endDownloadMeg:
Toast.makeText(TestMultiThreadDownLoadActivity.this,
"下载完成,马上安装", Toast.LENGTH_SHORT).show();
/*apk安装界面跳转*/
String filename = FileUtil.getFileName(url);
String str = "/myfile/" + filename;
String fileName = Environment.getExternalStorageDirectory() + str;
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(new File(fileName)),
"application/vnd.android.package-archive");
startActivity(intent);
break;
}
super.handleMessage(msg);
}
};
}
///开始下载软件
public void startDownLoad(View view) {
if (TextUtils.isEmpty(editText.getText().toString())) {
Toast.makeText(this, "你输入下载文件地址", Toast.LENGTH_SHORT).show();
return;
} else {
url = editText.getText().toString();
}
//启动线程初始化下载参数
mUpdateUIThread = new UpdateUIThread(handler, url,
FileUtil.setMkdir(this) + File.separator, FileUtil.getFileName(url));
pb = new ProgressDialog(this);
pb.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pb.show();
mUpdateUIThread.start();
}
}
例子代码太长,只能给你一部分,如果想看完整例子代码,请去360手机助手下载安卓学习手册,点击里面的源码可以查看完成代码,方面快速,里面还有安卓的其它小例子,共108个。