//布局
参考博客:https://www.cnblogs.com/cainiaodongdong/p/7880723.html
推荐博客下载完播放视频:http://m.blog.csdn.net/c_bulrush/article/details/78611097
//主布局
xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.bwei.test.lx_week_three.activity.MainActivity"> <com.youth.banner.Banner android:id="@+id/banner" android:layout_width="match_parent" android:layout_height="200dp" android:layout_alignParentTop="true" android:layout_alignParentLeft="true" android:layout_alignParentStart="true"> com.youth.banner.Banner> <RelativeLayout android:id="@+id/title" android:layout_width="match_parent" android:layout_below="@+id/banner" android:layout_height="wrap_content"> <TextView android:layout_width="wrap_content" android:text="免费试听" android:textSize="20sp" android:layout_marginLeft="10dp" android:layout_height="wrap_content" /> <TextView android:layout_width="wrap_content" android:text="查看全部" android:layout_alignParentRight="true" android:layout_marginRight="10dp" android:textSize="20sp" android:layout_height="wrap_content" /> RelativeLayout> <android.support.v7.widget.RecyclerView android:id="@+id/rlv" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_below="@+id/title"> android.support.v7.widget.RecyclerView> RelativeLayout>//item
xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" xmlns:fresco="http://schemas.android.com/apk/res-auto"> <com.facebook.drawee.view.SimpleDraweeView android:id="@+id/my_image_view" android:layout_width="130dp" android:layout_height="130dp" fresco:placeholderImage="@mipmap/ic_launcher" /> <RelativeLayout android:layout_width="match_parent" android:layout_toRightOf="@+id/my_image_view" android:layout_height="130dp"> <TextView android:id="@+id/tv_title" android:layout_width="match_parent" android:padding="20dp" android:layout_height="wrap_content" /> <TextView android:id="@+id/tv_other" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="5dp" android:layout_below="@+id/tv_title" android:padding="20dp" /> RelativeLayout> RelativeLayout>//主类
public class MainActivity extends BaseActivity//适配器implements IHomeView { private Banner mBanner; private RelativeLayout mTitle; private RecyclerView mRlv; List list; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Fresco.initialize(this); initView(); presenter.show(); } private void initView() { mBanner = (Banner) findViewById(R.id.banner); mTitle = (RelativeLayout) findViewById(R.id.title); mRlv = (RecyclerView) findViewById(R.id.rlv); list=new ArrayList<>(); } @Override protected void createPresnter() { presenter=new HomePresenter(this); } @Override protected void init() { } @Override protected void onStart() { super.onStart(); mBanner.startAutoPlay(); } @Override protected void onStop() { super.onStop(); mBanner.stopAutoPlay(); } @Override public void showData(final Bean bean) { for (int i = 0; i list.add(bean.getData().get(i).getImage_url()); Log.i("=============", "showData: "+list.toString()); } mBanner.setImageLoader(new GlideImageLoader()); mBanner.setImages(list); mBanner.start(); //展示RecyclerView数据 mRlv.setLayoutManager(new LinearLayoutManager(this)); MyRecyclerViewAdapter myRecyclerViewAdapter = new MyRecyclerViewAdapter(this, bean); mRlv.setAdapter(myRecyclerViewAdapter); myRecyclerViewAdapter.setOnItemClickListener(new MyRecyclerViewAdapter.onItemClickListener() { @Override public void OnItemClick(View view, int position) { String vedio_url = bean.getData().get(position).getVedio_url(); Intent intent=new Intent(MainActivity.this,OtherActivity.class); intent.putExtra("vedio_url",vedio_url); startActivity(intent); } }); }
public class MyRecyclerViewAdapter extends RecyclerView.Adapter//BaseActivity{ Context context; Bean bean; public MyRecyclerViewAdapter(Context context, Bean bean) { this.context = context; this.bean = bean; } @Override public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view=View.inflate(context,R.layout.item,null); view.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { listener.OnItemClick(view, (Integer) view.getTag()); } }); MyViewHolder holder=new MyViewHolder(view); return holder; } @Override public void onBindViewHolder(MyViewHolder holder, int position) { holder.tv.setText(bean.getData().get(position).getTitle()); holder.tv2.setText(bean.getData().get(position).getContent()); holder.sdw.setController(Fresco.newDraweeControllerBuilder().setUri(bean.getData().get(position).getImage_url()).build()); holder.itemView.setTag(position); } @Override public int getItemCount() { return bean.getData() == null ? 0 : bean.getData().size(); } onItemClickListener listener; public void setOnItemClickListener(onItemClickListener listener){ this.listener=listener; } public interface onItemClickListener { void OnItemClick(View view, int position); } class MyViewHolder extends RecyclerView.ViewHolder { SimpleDraweeView sdw; TextView tv, tv2; public MyViewHolder(View itemView) { super(itemView); sdw = itemView.findViewById(R.id.my_image_view); tv = itemView.findViewById(R.id.tv_title); tv2 = itemView.findViewById(R.id.tv_other); } }
public abstract class BaseActivity <T extends IPresenter> extends AppCompatActivity { public T presenter; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); createPresnter(); } protected abstract void createPresnter(); protected abstract void init(); }//
BaseService
public class BaseService { private static OkHttpClient.Builder httpClient = new OkHttpClient.Builder(); private static Retrofit.Builder builder = new Retrofit.Builder() .baseUrl("http://result.eolinker.com/") .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()); public static <S> S createService(Class<S> serviceClass) { Retrofit retrofit = builder.client(httpClient.build()).build(); return retrofit.create(serviceClass); } }//Bean
public class Bean { /** * code : 200 * data : [{"content":"习近平举行仪式欢迎加蓬总统访华","id":10000,"image_url":"http://pic32.nipic.com/20130817/9745430_101836881000_2.jpg","title":"今日头条","type":1,"vedio_url":"http://2449.vod.myqcloud.com/2449_bfbbfa3cea8f11e5aac3db03cda99974.f20.mp4"},{"content":"习近平举行仪式欢迎加蓬总统访华","id":10001,"image_url":"http://pic15.nipic.com/20110630/6322714_105943746342_2.jpg","title":"往期故事","type":2,"vedio_url":"https://wdl.wallstreetcn.com/41aae4d2-390a-48ff-9230-ee865552e72d"},{"content":"这个市的书记市长双双被约谈 引发震动","id":10002,"image_url":"http://pic48.nipic.com/file/20140916/2531170_195153248000_2.jpg","title":"讨论天下","type":3,"vedio_url":"http://video.jiecao.fm/5/1/%E8%87%AA%E5%8F%96%E5%85%B6%E8%BE%B1.mp4"},{"content":"\u201c乔丹\u201d商标是否侵权 4年官司迎最高法判决 调查","id":10003,"image_url":"http://img.taopic.com/uploads/allimg/140626/240469-1406261S24553.jpg","title":"我的珍爱","type":4,"vedio_url":"http://2449.vod.myqcloud.com/2449_bfbbfa3cea8f11e5aac3db03cda99974.f20.mp4"},{"content":"黑龙江稻农收入暴涨组团进城买房 有人买十多套","id":10004,"image_url":"http://pic77.nipic.com/file/20150911/21721561_155058651000_2.jpg","title":"我的未来","type":5,"vedio_url":"http://video.jiecao.fm/5/1/%E8%87%AA%E5%8F%96%E5%85%B6%E8%BE%B1.mp4"},{"content":"印尼6.4级地震致97死 专家称当地防震意识差","id":10005,"image_url":"http://img4.duitang.com/uploads/item/201603/18/20160318103156_cziuY.jpeg","title":"东芝","type":6,"vedio_url":"http://ips.ifeng.com/video19.ifeng.com/video09/2014/06/16/1989823-102-086-0009.mp4"}] * msg : 成功 */ private int code; private String msg; private List//M层data; public int getCode() { return code; } public void setCode(int code) { this.code = code; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public List getData() { return data; } public void setData(List data) { this.data = data; } public static class DataBean { /** * content : 习近平举行仪式欢迎加蓬总统访华 * id : 10000 * image_url : http://pic32.nipic.com/20130817/9745430_101836881000_2.jpg * title : 今日头条 * type : 1 * vedio_url : http://2449.vod.myqcloud.com/2449_bfbbfa3cea8f11e5aac3db03cda99974.f20.mp4 */ private String content; private int id; private String image_url; private String title; private int type; private String vedio_url; public String getContent() { return content; } public void setContent(String content) { this.content = content; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getImage_url() { return image_url; } public void setImage_url(String image_url) { this.image_url = image_url; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public int getType() { return type; } public void setType(int type) { this.type = type; } public String getVedio_url() { return vedio_url; } public void setVedio_url(String vedio_url) { this.vedio_url = vedio_url; } } }
public interface IHomeModel { void getData(HomeCallback callback); interface HomeCallback{ void homeComplete(Bean bean); } }
public class HomeModel implements IHomeModel{ @Override public void getData(final HomeCallback callback) { BaseService.createService(GetInterface.class).getData_Banner() .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Observer//View层() { @Override public void onSubscribe(Disposable d) { } @Override public void onNext(Bean bean) { callback.homeComplete(bean); } @Override public void onError(Throwable e) { } @Override public void onComplete() { } }); } }
public interface IHomeView { void showData(Bean bean); }//Presenter层
public interface IPresenter<T> { void attch(T view); void disattch(); }
public class HomePresenter implements IPresenter//retrofit{ IHomeModel model; SoftReference srf; public HomePresenter(IHomeView view) { model = new HomeModel(); attch(view); } public void show(){ model.getData(new IHomeModel.HomeCallback() { @Override public void homeComplete(Bean bean) { srf.get().showData(bean); } }); } @Override public void attch(IHomeView view) { srf = new SoftReference (view); } @Override public void disattch() { srf =null; } }
public interface GetInterface { @GET("iYXEPGn4e9c6dafce6e5cdd23287d2bb136ee7e9194d3e9?uri=vedio") ObservableutilsgetData_Banner(); /* @Streaming*//*大文件需要加入这个判断,防止下载过程中写入到内存中*//* @GET Observable download(@Header("RANGE") String start, @Url String url);*/ @Streaming @GET Observabledownload(@Header("RANGE") String start, @Url String url); }
public class GlideImageLoader extends ImageLoader { @Override public void displayImage(Context context, Object path, ImageView imageView) { Glide.with(context).load(path).into(imageView); } }//build.gradle
apply plugin: 'com.android.application' apply plugin: 'org.greenrobot.greendao' android { compileSdkVersion 26 buildToolsVersion "26.0.1" defaultConfig { applicationId "com.bwei.test.lx_week_three" minSdkVersion 15 targetSdkVersion 26 multiDexEnabled true versionCode 1 versionName "1.0" //testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } } dependencies { //Gson converter //RxJava2 Adapter //compile files('libs/okhttp-3.9.0.jar') compile 'com.android.support:appcompat-v7:26.+' compile 'com.android.support.constraint:constraint-layout:1.0.2' compile 'com.android.support:recyclerview-v7:26.0.0-alpha1' compile 'com.youth.banner:banner:1.4.9' compile 'com.facebook.fresco:fresco:0.11.0' compile 'io.reactivex.rxjava2:rxjava:2.1.1' compile 'io.reactivex.rxjava2:rxandroid:2.0.1' compile 'com.squareup.retrofit2:retrofit:2.2.0' compile 'com.squareup.retrofit2:converter-gson:2.2.0' compile 'com.squareup.retrofit2:adapter-rxjava2:2.2.0' compile 'com.github.bumptech.glide:glide:3.7.0' compile 'org.greenrobot:greendao:3.2.0' testCompile 'junit:junit:4.12' }
//在外部的依赖中加入
buildscript { repositories { jcenter() mavenCentral() } dependencies { classpath 'com.android.tools.build:gradle:2.3.1' classpath 'org.greenrobot:greendao-gradle-plugin:3.2.1' } }//OtherActivity布局
xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.bwei.test.lx_week_three.activity.OtherActivity"> <TextView android:id="@+id/textView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" android:layout_alignParentTop="true" android:layout_marginLeft="23dp" android:layout_marginStart="23dp" android:layout_marginTop="18dp" android:text="TextView" /> <ProgressBar android:id="@+id/progressBar" style="?android:attr/progressBarStyleHorizontal" android:layout_width="fill_parent" android:layout_height="7.5dp" android:layout_below="@+id/textView" android:layout_marginRight="8dp" android:max="100" android:progress="100" android:visibility="visible" /> <Button android:id="@+id/start" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:layout_toEndOf="@+id/textView" android:layout_toRightOf="@+id/textView" android:text="下载" /> <Button android:id="@+id/delete" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:layout_marginLeft="48dp" android:layout_marginStart="48dp" android:layout_toEndOf="@+id/start" android:layout_toRightOf="@+id/start" android:text="暂停" /> RelativeLayout>
//Other类
public class OtherActivity extends AppCompatActivity { private static final String TAG = MainActivity.class.getSimpleName(); private ProgressBar mProgressBar; private Button start; private Button pause; private TextView total; private int max; private DownloadUtil mDownloadUtil; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_other); total = (TextView) findViewById(R.id.textView); start = (Button) findViewById(R.id.start); pause = (Button) findViewById(R.id.delete); mProgressBar = (ProgressBar) findViewById(R.id.progressBar); Intent intent=getIntent(); String urlString = intent.getStringExtra("vedio_url"); // String urlString = "http://2449.vod.myqcloud.com/2449_22ca37a6ea9011e5acaaf51d105342e3.f20.mp4"; String localPath = getCacheDir() + "/local2"; mDownloadUtil = new DownloadUtil(2, localPath, "adc.mp4", urlString, this); mDownloadUtil.setOnDownloadListener(new DownloadUtil.OnDownloadListener() { @Override public void downloadStart(int fileSize) { // TODO Auto-generated method stub Log.w(TAG, "fileSize::" + fileSize); max = fileSize; mProgressBar.setMax(fileSize); } @Override public void downloadProgress(int downloadedSize) { // TODO Auto-generated method stub Log.w(TAG, "Compelete::" + downloadedSize); mProgressBar.setProgress(downloadedSize); total.setText((int) downloadedSize * 100 / max + "%"); } @Override public void downloadEnd() { // TODO Auto-generated method stub Log.w(TAG, "ENd"); } }); start.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { // TODO Auto-generated method stub mDownloadUtil.start(); } }); pause.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { // TODO Auto-generated method stub mDownloadUtil.pause(); } }); }
//多线程断点下载所用
四个类
public class DownlaodSqlTool { /** * 创建下载的具体信息 */ public void insertInfos(Listinfos) { for (DownloadInfo info : infos) { User user = new User(null, info.getThreadId(), info.getStartPos(), info.getEndPos(), info.getCompeleteSize(), info.getUrl()); userDao.insert(user); } } /** * 得到下载具体信息 */ public List getInfos(String urlstr) { List list = new ArrayList (); List list1 = userDao.queryBuilder().where(UserDao.Properties.Url.eq(urlstr)).build().list(); for (User user : list1) { DownloadInfo infoss = new DownloadInfo( user.getThread_id(), user.getStart_pos(), user.getEnd_pos(), user.getCompelete_size(), user.getUrl()); Log.d("main-----", infoss.toString()); list.add(infoss); } return list; } /** * 更新数据库中的下载信息 */ public void updataInfos(int threadId, int compeleteSize, String urlstr) { User user = userDao.queryBuilder() .where(UserDao.Properties.Thread_id.eq(threadId), UserDao.Properties.Url.eq(urlstr)).build().unique(); user.setCompelete_size(compeleteSize); userDao.update(user); } /** * 下载完成后删除数据库中的数据 */ public void delete(String url) { userDao.deleteAll(); } }
public class DownloadHttpTool { /** * 利用Http协议进行多线程下载具体实践类 */ private static final String TAG = DownloadHttpTool.class.getSimpleName(); private int threadCount;//线程数量 private String urlstr;//URL地址 private Context mContext; private Handler mHandler; private ListdownloadInfos;//保存下载信息的类 private String localPath;//目录 private String fileName;//文件名 private int fileSize; private DownlaodSqlTool sqlTool;//文件信息保存的数据库操作类 private enum Download_State { Downloading, Pause, Ready;//利用枚举表示下载的三种状态 } private Download_State state = Download_State.Ready;//当前下载状态 private int globalCompelete = 0;//所有线程下载的总数 public DownloadHttpTool(int threadCount, String urlString, String localPath, String fileName, Context context, Handler handler) { super(); this.threadCount = threadCount; this.urlstr = urlString; this.localPath = localPath; this.mContext = context; this.mHandler = handler; this.fileName = fileName; sqlTool = new DownlaodSqlTool(); } //在开始下载之前需要调用ready方法进行配置 public void ready() { Log.w(TAG, "ready"); globalCompelete = 0; downloadInfos = sqlTool.getInfos(urlstr); if (downloadInfos.size() == 0) { initFirst(); } else { File file = new File(localPath + "/" + fileName); if (!file.exists()) { sqlTool.delete(urlstr); initFirst(); } else { fileSize = downloadInfos.get(downloadInfos.size() - 1) .getEndPos(); for (DownloadInfo info : downloadInfos) { globalCompelete += info.getCompeleteSize(); } Log.w(TAG, "globalCompelete:::" + globalCompelete); } } } public void start() { Log.w(TAG, "start"); if (downloadInfos != null) { if (state == Download_State.Downloading) { return; } state = Download_State.Downloading; for (DownloadInfo info : downloadInfos) { Log.v(TAG, "startThread"); new DownloadThread(info.getThreadId(), info.getStartPos(), info.getEndPos(), info.getCompeleteSize(), info.getUrl()).start(); } } } public void pause() { state = Download_State.Pause; } public void delete() { compelete(); File file = new File(localPath + "/" + fileName); file.delete(); } public void compelete() { sqlTool.delete(urlstr); } public int getFileSize() { return fileSize; } public int getCompeleteSize() { return globalCompelete; } //第一次下载初始化 private void initFirst() { Log.w(TAG, "initFirst"); try { URL url = new URL(urlstr); HttpURLConnection connection = (HttpURLConnection) url .openConnection(); connection.setConnectTimeout(5000); connection.setRequestMethod("GET"); fileSize = connection.getContentLength(); Log.w(TAG, "fileSize::" + fileSize); File fileParent = new File(localPath); if (!fileParent.exists()) { fileParent.mkdir(); } File file = new File(fileParent, fileName); if (!file.exists()) { file.createNewFile(); } // 本地访问文件 RandomAccessFile accessFile = new RandomAccessFile(file, "rwd"); accessFile.setLength(fileSize); accessFile.close(); connection.disconnect(); } catch (Exception e) { e.printStackTrace(); } int range = fileSize / threadCount; downloadInfos = new ArrayList (); for (int i = 0; i < threadCount - 1; i++) { DownloadInfo info = new DownloadInfo(i, i * range, (i + 1) * range - 1, 0, urlstr); downloadInfos.add(info); } DownloadInfo info = new DownloadInfo(threadCount - 1, (threadCount - 1) * range, fileSize - 1, 0, urlstr); downloadInfos.add(info); sqlTool.insertInfos(downloadInfos); } //自定义下载线程 private class DownloadThread extends Thread { private int threadId; private int startPos; private int endPos; private int compeleteSize; private String urlstr; private int totalThreadSize; public DownloadThread(int threadId, int startPos, int endPos, int compeleteSize, String urlstr) { this.threadId = threadId; this.startPos = startPos; this.endPos = endPos; totalThreadSize = endPos - startPos + 1; this.urlstr = urlstr; this.compeleteSize = compeleteSize; } @Override public void run() { HttpURLConnection connection = null; RandomAccessFile randomAccessFile = null; InputStream is = null; try { randomAccessFile = new RandomAccessFile(localPath + "/" + fileName, "rwd"); randomAccessFile.seek(startPos + compeleteSize); URL url = new URL(urlstr); connection = (HttpURLConnection) url.openConnection(); connection.setConnectTimeout(5000); connection.setRequestMethod("GET"); connection.setRequestProperty("Range", "bytes=" + (startPos + compeleteSize) + "-" + endPos); is = connection.getInputStream(); byte[] buffer = new byte[1024]; int length = -1; while ((length = is.read(buffer)) != -1) { randomAccessFile.write(buffer, 0, length); compeleteSize += length; Message message = Message.obtain(); message.what = threadId; message.obj = urlstr; message.arg1 = length; mHandler.sendMessage(message); sqlTool.updataInfos(threadId, compeleteSize, urlstr); Log.w(TAG, "Threadid::" + threadId + " compelete::" + compeleteSize + " total::" + totalThreadSize); if (compeleteSize >= totalThreadSize) { break; } if (state != Download_State.Downloading) { break; } } } catch (Exception e) { e.printStackTrace(); } finally { try { if (is != null) { is.close(); } randomAccessFile.close(); connection.disconnect(); } catch (Exception e) { e.printStackTrace(); } } } } }
public class DownloadInfo { /** * 保存每个下载线程下载信息类 * */ private int threadId;// 下载器id private int startPos;// 开始点 private int endPos;// 结束点 private int compeleteSize;// 完成度 private String url;// 下载文件的URL地址 public DownloadInfo(int threadId, int startPos, int endPos, int compeleteSize, String url) { this.threadId = threadId; this.startPos = startPos; this.endPos = endPos; this.compeleteSize = compeleteSize; this.url = url; } public DownloadInfo() { } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public int getThreadId() { return threadId; } public void setThreadId(int threadId) { this.threadId = threadId; } public int getStartPos() { return startPos; } public void setStartPos(int startPos) { this.startPos = startPos; } public int getEndPos() { return endPos; } public void setEndPos(int endPos) { this.endPos = endPos; } public int getCompeleteSize() { return compeleteSize; } public void setCompeleteSize(int compeleteSize) { this.compeleteSize = compeleteSize; } @Override public String toString() { return "DownloadInfo [threadId=" + threadId + ", startPos=" + startPos + ", endPos=" + endPos + ", compeleteSize=" + compeleteSize + "]"; } }
public class DownloadUtil { private DownloadHttpTool mDownloadHttpTool; private OnDownloadListener onDownloadListener; private int fileSize; private int downloadedSize = 0; @SuppressLint("HandlerLeak") private Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { // TODO Auto-generated method stub super.handleMessage(msg); int length = msg.arg1; synchronized (this) {//加锁保证已下载的正确性 downloadedSize += length; } if (onDownloadListener != null) { onDownloadListener.downloadProgress(downloadedSize); } if (downloadedSize >= fileSize) { mDownloadHttpTool.compelete(); if (onDownloadListener != null) { onDownloadListener.downloadEnd(); } } } }; public DownloadUtil(int threadCount, String filePath, String filename, String urlString, Context context) { mDownloadHttpTool = new DownloadHttpTool(threadCount, urlString, filePath, filename, context, mHandler); } //下载之前首先异步线程调用ready方法获得文件大小信息,之后调用开始方法 public void start() { new AsyncTaskUserBean() { @Override protected Void doInBackground(Void... arg0) { // TODO Auto-generated method stub mDownloadHttpTool.ready(); return null; } @Override protected void onPostExecute(Void result) { // TODO Auto-generated method stub super.onPostExecute(result); fileSize = mDownloadHttpTool.getFileSize(); downloadedSize = mDownloadHttpTool.getCompeleteSize(); Log.w("Tag", "downloadedSize::" + downloadedSize); if (onDownloadListener != null) { onDownloadListener.downloadStart(fileSize); } mDownloadHttpTool.start(); } }.execute(); } public void pause() { mDownloadHttpTool.pause(); } public void delete(){ mDownloadHttpTool.delete(); } public void reset(){ mDownloadHttpTool.delete(); start(); } public void setOnDownloadListener(OnDownloadListener onDownloadListener) { this.onDownloadListener = onDownloadListener; } //下载回调接口 public interface OnDownloadListener { public void downloadStart(int fileSize); public void downloadProgress(int downloadedSize);//记录当前所有线程下总和 public void downloadEnd(); } }
@Entity public class User { @Id private Long id; private Integer thread_id; private Integer start_pos; private Integer end_pos; private Integer compelete_size; private String url; @Generated(hash = 2041931179) public User(Long id, Integer thread_id, Integer start_pos, Integer end_pos, Integer compelete_size, String url) { this.id = id; this.thread_id = thread_id; this.start_pos = start_pos; this.end_pos = end_pos; this.compelete_size = compelete_size; this.url = url; } @Generated(hash = 586692638) public User() { } public Long getId() { return this.id; } public void setId(Long id) { this.id = id; } public Integer getThread_id() { return this.thread_id; } public void setThread_id(Integer thread_id) { this.thread_id = thread_id; } public Integer getStart_pos() { return this.start_pos; } public void setStart_pos(Integer start_pos) { this.start_pos = start_pos; } public Integer getEnd_pos() { return this.end_pos; } public void setEnd_pos(Integer end_pos) { this.end_pos = end_pos; } public Integer getCompelete_size() { return this.compelete_size; } public void setCompelete_size(Integer compelete_size) { this.compelete_size = compelete_size; } public String getUrl() { return this.url; } public void setUrl(String url) { this.url = url; } }
//节操播放
compile 'fm.jiecao:jiecaovideoplayer:4.8.3'
<fm.jiecao.jcvideoplayer_lib.JCVideoPlayerStandard android:layout_below="@+id/progressBar" android:id="@+id/player_list_video" android:layout_width="match_parent" android:layout_height="220dp" />
@Override public void downloadEnd() { // TODO Auto-generated method stub Log.w(TAG, "ENd"); JCVideoPlayerStandard player = (JCVideoPlayerStandard) findViewById(R.id.player_list_video); boolean setUp = player.setUp(localPath+"adc.mp4", JCVideoPlayer.SCREEN_LAYOUT_LIST, ""); if (setUp) { Glide.with(OtherActivity.this).load("http://a4.att.hudong.com/05/71/01300000057455120185716259013.jpg").into(player.thumbImageView); }