/**
* 下载方法
*/
private void downLoadDatabase() {
final String choose = "111111";//这里给个写死的名称 真实的自己获取或者设置
String serverIP = getIpAddress();
String url = "https://haokan.baidu.com/v?vid=13639811334010665664&pd=bjh&fr=bjhauthor&type=video";
String strDBPath3 = Environment.getExternalStorageDirectory() + "/TIS- Smarthome/" + "download";//下载路径
Request request = new Request.Builder()
.url(url)
.build();
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.build();
Call mDownloadCall = okHttpClient.newCall(request);
mDownloadCall.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
//失败的时候回调,打印异常信息
Log.e(TAG, "onFailure: -------- " + e.getMessage());
}
@Override
public void onResponse(Call call, Response response) throws IOException {
ResponseBody body = response.body();
long totleBytes = body.contentLength();//得到文件的总大小
// long totleBytes=3
InputStream is = body.byteStream();//得到一个流文件
FileOutputStream fos = new FileOutputStream(strDBPath3);
byte[] buf = new byte[2048];
long currentBytes = 0L;
int len = 0;
//将文件写入本地(再次友情提示:记得权限问题)
while ((len = is.read(buf)) != -1) {
fos.write(buf, 0, len);
currentBytes += len;//每次写入的大小累
int progress = (int) ((currentBytes) / totleBytes);//转换得到当前下载的进度%
long finalCurrentBytes = currentBytes;
int finalLen = len;
runnable = new Runnable() {
public void run() {
SharedPreferences sh = getSharedPreferences("Login", MODE_PRIVATE);
SharedPreferences.Editor editor = sh.edit();
Double daixoa= Double.valueOf(totleBytes/1024/1024);
Double leiji= Double.valueOf(finalCurrentBytes/1024/1024);
Double sudu=Double.valueOf(finalLen/1024);
editor.putString("daxiao", daixoa + "M");
editor.putString("jindu", progress + "%");
editor.putString("leiji",leiji + "M");
editor.putString("sudu", sudu + "KB");
editor.putString("tupian", "");
editor.putString("name", "");
editor.putString("url", url);
handler.postDelayed(this, 1000);
//postDelayed(this,2000)方法安排一个Runnable对象到主线程队列中
}
};
XiaZaiModel xiaZaiModel = new XiaZaiModel();
xiaZaiModel.setMingzi("");
xiaZaiModel.setTupian("");
xiaZaiModel.setSudu(finalLen + "");
xiaZaiModel.setLeiji(finalCurrentBytes + "");
xiaZaiModel.setJindu(progress + "");
xiaZaiModel.setDaxiao(totleBytes + "");
xiaZaiModel.setUrl(url);
xiaZaiModelList.add(xiaZaiModel);
Log.e(TAG, "onResponse: --------- 下载进度:" + progress + "%" + "文件大小:" + totleBytes + "进度" + currentBytes + "大小" + len);
}
fos.flush();
fos.close();
is.close();
}
});
}
下载列表:
public class DownloadActivity extends Activity {
@BindView(R.id.yishangxan)
TextView yishangxan;
@BindView(R.id.weishangxian)
TextView weishangxian;
@BindView(R.id.list_xiazai)
ListView listXiazai;
@BindView(R.id.tv_quanuan)
TextView tvQuanuan;
@BindView(R.id.tv_shanchu)
TextView tvShanchu;
private DownloadManager downloadManager;
private Handler handler = new Handler();
private Runnable runnable;
public String daixiao, jindu, leiji, sudu, tupian, mingzi, url;
private XiaZaiAdapter adapter1;
private List<XiaZaiModel> xiaZaiModelList = new ArrayList<>();
private DownloadService.DownloadBinder downloadBinder;
private int dianji;
private ServiceConnection serviceConnection = new ServiceConnection() {
/**
* 活动与服务绑定成功后
* @param name
* @param service
*/
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
downloadBinder = (DownloadService.DownloadBinder) service;
}
/**
* 活动与服务解绑后
* @param name
*/
@Override
public void onServiceDisconnected(ComponentName name) {
}
};
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activitty_download);
ButterKnife.bind(this);
runnable = new Runnable() {
public void run() {
SharedPreferences sharedPreferences = getSharedPreferences("xiazai", MODE_PRIVATE);
daixiao = sharedPreferences.getString("daxiao", "");
jindu = sharedPreferences.getString("jindu", "");
leiji = sharedPreferences.getString("leiji", "");
sudu = sharedPreferences.getString("sudu", "");
tupian = sharedPreferences.getString("tupian", "");
mingzi = sharedPreferences.getString("name", "");
url = sharedPreferences.getString("url", "");
handler.postDelayed(this, 1000);
//postDelayed(this,2000)方法安排一个Runnable对象到主线程队列中
}
};
if (jindu.equals("100%")) {
} else {
adapter1 = new XiaZaiAdapter(DownloadActivity.this, R.layout.item_zhengzai_xiazai, xiaZaiModelList);
listXiazai.setAdapter(adapter1);
listXiazai.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (dianji==1) {
downloadBinder.cancelDownload();
dianji=0;
}else {
downloadBinder.pauseDownload();
dianji=1;
}
}
});
}
}
}
下载列表页面
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_marginLeft="@dimen/dp_20"
android:layout_marginTop="@dimen/dp_20">
<TextView
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:text="已下载"
android:padding="10dp"
android:textColor="@color/red1"
android:gravity="center"
android:id="@+id/yishangxan"
android:background="#e5e5ee"
/>
<TextView
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:text="正在下载"
android:gravity="center"
android:layout_marginLeft="@dimen/dp_20"
android:padding="@dimen/dp_10"
android:id="@+id/weishangxian"
android:background="#e5e5ee"/>
</LinearLayout>
<LinearLayout
android:id="@+id/ll_yxiazai"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:orientation="vertical">
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/list_xiazai"
android:visibility="gone"/>
<include layout="@layout/item_zhengzai_xiazai"/>
<include layout="@layout/item_zhengzai_xiazai"/>
<include layout="@layout/item_zhengzai_xiazai"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="@+id/tv_quanuan"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:text="全选"
android:gravity="center"
android:padding="@dimen/dp_10"
android:textColor="@color/c6"
android:textSize="@dimen/sp_16"/>
<TextView
android:id="@+id/tv_shanchu"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:text="删除"
android:gravity="center"
android:padding="@dimen/dp_10"
android:textColor="@color/c6"
android:textSize="@dimen/sp_16"/>
</LinearLayout>
</LinearLayout>
下载列表适配器
public class XiaZaiAdapter extends BaseAdapter {
protected LayoutInflater inflater;
protected int resource;
private DownloadActivity context;
protected List<XiaZaiModel> list;
private String userId;
public XiaZaiAdapter(DownloadActivity context, int resource, List<XiaZaiModel> list) {
inflater = LayoutInflater.from(context);
this.context = context;
this.resource = resource;
if (list == null) {
this.list = new ArrayList<>();
} else {
this.list = list;
}
}
@Override
public int getCount() {
return list.size() ;
}
@Override
public Object getItem(int position) {
return list.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// final VideoDomain.DataBean dingdan = new VideoDomain.DataBean();
// VideoDomain.DataBean dingdan = (VideoDomain.DataBean) getItem(position);
// VideoDomain dingdan = (VideoDomain) getItem(position);
ViewHolder vh = null;
if (convertView == null) {
convertView = inflater.inflate(resource, null);
vh = new ViewHolder();
vh.dianying = (ImageView) convertView.findViewById(R.id.iv_xiazai_toupin);
vh.name = (TextView) convertView.findViewById(R.id.tv_xiazai_mingcheng);
vh.sudu = (TextView) convertView.findViewById(R.id.tv_xiazai_sudu);
vh.leiji = (TextView) convertView.findViewById(R.id.tv_xiazai_leiji);
vh.daixiao = (TextView) convertView.findViewById(R.id.tv_xiazai_zongdaxiao);
vh.progressBar = (ProgressBar) convertView.findViewById(R.id.progressBar);
convertView.setTag(vh);
} else {
vh = (ViewHolder) convertView.getTag();
}
vh.daixiao.setText(context.daixiao);
vh.progressBar.setProgress(Integer.parseInt(context.jindu));
vh.leiji.setText(context.leiji);
vh.sudu.setText(context.sudu);
vh.name.setText(context.mingzi);
Picasso
.with(context)
.load(context.tupian)
.placeholder(context.getResources().getDrawable(R.mipmap.zhanwei))//图片加载中显示
.into(vh.dianying);
return convertView;
}
public static class ViewHolder {
//public final View root;
private TextView name;
private TextView sudu;
private ImageView dianying;
private TextView daixiao;
private TextView leiji;
private ProgressBar progressBar;
}
/**
* @ClassName: LishiJiLuadapter
* @Description: java类作用描述
* @Author: 碧血染银枪
* @CreateDate: 2020/4/16 17:37
* @UpdateUser: 更新者
* @UpdateDate: 2020/4/16 17:37
* @UpdateRemark: 更新说明
*/
}
下载适配器页面
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
android:layout_height="@dimen/dp_80"
android:orientation="horizontal"
android:layout_marginRight="@dimen/dp_20">
<ImageView
android:layout_width="@dimen/dp_100"
android:layout_height="@dimen/dp_80"
android:src="@mipmap/zhanwei"
android:id="@+id/iv_xiazai_toupin"
android:layout_marginLeft="@dimen/dp_20"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="@+id/tv_xiazai_mingcheng"
android:layout_width="wrap_content"
android:layout_weight="1"
android:layout_height="0dp"
android:text="电影名称"
android:layout_marginLeft="@dimen/dp_10"
android:textSize="14sp"
android:textColor="@color/c6"/>
<ProgressBar
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/progressBar"
android:layout_gravity="center_horizontal"
android:max="100"
android:layout_marginLeft="@dimen/dp_10"
android:progress="20"
android:startColor="@color/red1"
android:centerColor="#ff5a5d5a"
android:centerY="0.75"
android:endColor="#ff747674"
android:angle="0"
android:indeterminate="false"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_weight="1"
android:layout_height="0dp"
android:orientation="horizontal">
<TextView
android:id="@+id/tv_xiazai_sudu"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:text="15kb/s"
android:layout_marginLeft="@dimen/dp_10"
android:textSize="14sp"
android:textColor="#999999"/>
<TextView
android:id="@+id/tv_xiazai_leiji"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="15kb"
android:layout_marginLeft="@dimen/dp_10"
android:textSize="14sp"
android:textColor="#999999"/>
<TextView
android:id="@+id/tv_xiazai_zongdaxiao"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="/15kb"
android:textSize="14sp"
android:textColor="#999999"/>
</LinearLayout>
</LinearLayout>
</LinearLayout>
下载Service
public class DownloadService extends Service {
private DownloadFileTask downloadFileTask;
// 下载地址
private String downloadUrl;
private static final String TAG = "DownloadService";
// 下载状态的回调
private DownloadListener listener = new DownloadListener() {
/**
* 更新下载进度状态
* @param progress
*/
@Override
public void onProgress(int progress) {
Log.d(TAG, "onProgress: -------" + progress);
getNotificationManager().notify(1, getNotification("Downloading", progress));
}
/**
* 下载成功
*/
@Override
public void onSuccess() {
Log.d(TAG, "onSuccess: -------------");
downloadFileTask = null;
//下载成功时将前台服务通知关闭,并创建一个下载成功的通知
stopForeground(true);
getNotificationManager().notify(1, getNotification("Download Success", -1));
Toast.makeText(DownloadService.this, "Download Success", Toast.LENGTH_SHORT).show();
}
/**
* 下载失败
*/
@Override
public void onFailed() {
Log.d(TAG, "onFailed: -------------");
downloadFileTask = null;
// 下载失败时将前台服务通知关闭,并创建一个下载失败的通知
stopForeground(true);
getNotificationManager().notify(1, getNotification("Download Failed", -1));
Toast.makeText(DownloadService.this, "Download Failed", Toast.LENGTH_SHORT).show();
}
/**
* 下载暂停
*/
@Override
public void onPaused() {
Log.d(TAG, "onPaused: -------------");
downloadFileTask = null;
Toast.makeText(DownloadService.this, "Download Paused", Toast.LENGTH_SHORT).show();
}
/**
* 下载取消
*/
@Override
public void onCanceled() {
Log.d(TAG, "onCanceled: -------------");
downloadFileTask = null;
stopForeground(true);
Toast.makeText(DownloadService.this, "Download Canceled", Toast.LENGTH_SHORT).show();
}
};
DownloadBinder mBinder = new DownloadBinder();
/**
* 返回这个DownloadBinder 实例
*
* @param intent
* @return
*/
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
// 创建 DownloadBinder 实例
public class DownloadBinder extends Binder {
// 开始下载
public void startDownload(String url) {
Log.d(TAG, "startDownload--------: 开始下载");
if (downloadFileTask == null) {
downloadUrl = url;
downloadFileTask = new DownloadFileTask(listener);
downloadFileTask.execute(downloadUrl);
startForeground(1, getNotification("DownLoading", 0));
Toast.makeText(DownloadService.this, "Downloading", Toast.LENGTH_SHORT).show();
}
}
// 暂停下载
public void pauseDownload() {
Log.d(TAG, "pauseDownload--------: 暂停下载");
if (downloadFileTask != null) {
downloadFileTask.pauseDownload();
}
}
// 取消下载
public void cancelDownload() {
Log.d(TAG, "cancelDownload--------: 取消下载---" + downloadFileTask);
if (downloadFileTask != null) {
downloadFileTask.cancelDownload();
} else {
if (downloadUrl != null) {
// 先暂停后取消 取消下载时需将文件删除,并通知关闭
String fileName = downloadUrl.substring(downloadUrl.lastIndexOf("/"));
String directory = Environment.getExternalStoragePublicDirectory
(Environment.DIRECTORY_DOWNLOADS).getPath();
File file = new File(directory + fileName);
if (file.exists()) {
file.delete();
}
getNotificationManager().cancel(1);
stopForeground(true);
Toast.makeText(DownloadService.this, "Canceled", Toast.LENGTH_SHORT).show();
}
}
}
}
/**
* 获取通知栏管理器
*
* @return
*/
public NotificationManager getNotificationManager() {
return (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
}
/**
* 设置通知栏的样式 并获取通知栏的实例
*
* @param title
* @param progress
* @return
*/
private Notification getNotification(String title, int progress) {
Intent[] intents = new Intent[]{(new Intent(this, DownloadActivity.class))};
PendingIntent pi = PendingIntent.getActivities(this, 0, intents, 0);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
builder.setSmallIcon(R.mipmap.ic_launcher);
builder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher));
builder.setContentIntent(pi);
builder.setContentTitle(title);
if (progress > 0) {
builder.setContentText(progress + "%");
builder.setProgress(100, progress, false);
}
return builder.build();
}
}
本文详细介绍了在安卓设备上下载及管理应用的具体实现方法,包括使用OkHttp进行网络请求、下载进度跟踪、下载任务的暂停与取消,以及通过Service和BroadcastReceiver实现下载任务的后台管理和通知。同时,文章还展示了如何设计下载列表页面和适配器,以及如何使用SharedPreferences存储下载信息。

3万+

被折叠的 条评论
为什么被折叠?



