Adpter_showadpter
public class ShowAdapter extends RecyclerView.Adapter<ShowAdapter.MyViewHolder> implements View.OnClickListener{
private Context context;
private List<Beans.DataBean> chalist;
//利用接口回调实现点击事件
//再实例,然后创建方法
private OnItemClickListener mOnItemClickListener = null;
//点击事件
@Override
public void onClick(View view) {
if (mOnItemClickListener!=null){
mOnItemClickListener.onItemClick(view, (Integer) view.getTag());
}
}
public static interface OnItemClickListener {
void onItemClick(View view , int position);
}
public ShowAdapter(Context context, List<Beans.DataBean> chalist) {
this.context = context;
this.chalist = chalist;
Log.i("33333", "onBindViewHolder: "+chalist.size());
}
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view=View.inflate(context, R.layout.rcy_item_line,null);
MyViewHolder holder=new MyViewHolder(view);
//调用点击
view.setOnClickListener(this);
return holder;
}
@Override
public void onBindViewHolder(MyViewHolder holder, int position) {
holder.tv.setText(chalist.get(position).getContent());
// String[] split = sousuolist.get(position).getImages().split("\\|");
// DraweeController ff= Fresco.newDraweeControllerBuilder()
// .setUri(String.valueOf(split[0]))
// .setAutoPlayAnimations(true)
// .build();
// holder.iv.setController(ff);
// String s =chalist.get(position).getList().get(0).getImages().split("\\|")[0];
DraweeController ff= Fresco.newDraweeControllerBuilder()
.setUri(chalist.get(position).getImage_url())
.setAutoPlayAnimations(true)
.build();
holder.iv.setController(ff);
//把条目的下标position设置给holder
holder.itemView.setTag(position);
//ImageLoader.getInstance().displayImage(list.get(position).getList().get(0).getImages(),holder.iv);
}
public void setmOnItemClickListener(OnItemClickListener listener){
this.mOnItemClickListener=listener;
}
@Override
public int getItemCount() {
return chalist.size();
}
class MyViewHolder extends RecyclerView.ViewHolder{
public TextView tv;
public SimpleDraweeView iv;
public MyViewHolder(View itemView) {
super(itemView);
tv = itemView.findViewById(R.id.tv);
iv = itemView.findViewById(R.id.img);
}
}
}
Img
public class Img extends ImageLoader {
@Override
public void displayImage(Context context, Object path, ImageView imageView) {
Glide.with(context)
.load(path)
.into(imageView);
}
}
model
public interface IModel {
void setObSerVer(Observer obSerVer);
}
public class MyModel implements IModel{
@Override
public void setObSerVer(Observer obSerVer) {
OkHttpClient okclient = new OkHttpClient.Builder().build();
RetrofitManager.getInstance(RequestApi.BASE_URL,okclient)
.setCreate(RequestApi.class)
.getData()
.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.io())
.subscribe(obSerVer);
}
}
Presenter
public class MyPresenter {
IModel model;
Iview view;
public MyPresenter(Iview view) {
this.view = view;
model=new MyModel();
}
public void loadData(){
model.setObSerVer(new Observer<Beans>() {
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
// Log.i("///", "onError: "+e);
}
@Override
public void onNext(Beans beans ) {
List<Beans.DataBean> data = beans.getData();
// Log.i("/////", "onNext: "+list.size());
view.setData(data);
}
});
}
}
view
public interface Iview {
void setData(List<Beans.DataBean> beanList);
}
utils_Api
public class Api {
public static final String BanUrl="http://result.eolinker.com/iYXEPGn4e9c6dafce6e5cdd23287d2bb136ee7e9194d3e9?uri=vedio";
}
utils_DialogUtils
public class DialogUtils {
public static long MAX_SIZE = 0;
public static long PROGRESS = -2;
// private static File file;
private static String path;
public static void showUpdataDialog(final Context context){
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("是否下载")
.setMessage("下载吧")
.setNegativeButton("以后再说", null)
.setPositiveButton("立即下载", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
// path= context.getCacheDir() + "/uri=vedio";
// new DownloadThread("http://result.eolinker.com/iYXEPGn4e9c6dafce6e5cdd23287d2bb136ee7e9194d3e9?uri=vedio", context.getCacheDir() + "/uri=vedio").start();
path= context.getCacheDir() + "/911Mothers_2010W-480p.mp4";
new DownloadThread("http://mirror.aarnet.edu.au/pub/TED-talks/911Mothers_2010W-480p.mp4", context.getCacheDir() + "/911Mothers_2010W-480p.mp4").start();
showProgress(context);
}
}).show();
}
public static interface autopPlay {
void autopplay(String path);
}
public static autopPlay play;
public static void setPlay(autopPlay autopPlay){
play=autopPlay;
};
public static void showProgress(final Context context){
final ProgressDialog pd = new ProgressDialog(context);
pd.setTitle("正在下载");
pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pd.setMax(100);
pd.show();
new AsyncTask<String, Integer, String>(){
@Override
protected String doInBackground(String... strings) {
while (PROGRESS+1 < MAX_SIZE){
SystemClock.sleep(100);
if (MAX_SIZE>0){
publishProgress((int)(PROGRESS * 100 / MAX_SIZE));
}
}
return null;
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
pd.dismiss();
play.autopplay(path);
// file=new File(context.getCacheDir() + "/911Mothers_2010W-480p.mp4");
// openApi(context,file);
Toast.makeText(context,"下载完成",Toast.LENGTH_SHORT).show();
}
@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
pd.setProgress(values[0]);
}
}.execute();
}
}
utils_RequestApi
public static final String BASE_URL = "http://result.eolinker.com/";
@GET("iYXEPGn4e9c6dafce6e5cdd23287d2bb136ee7e9194d3e9?uri=vedio")
Observable<Beans> getData();
utils_RetrofitManager
public class RetrofitManager {
private Retrofit mRetrofit;
private String baseUrl;
OkHttpClient client;
private static RetrofitManager mRetrofitManager;
private RetrofitManager(String baseUrl,OkHttpClient client){
this.baseUrl=baseUrl;
this.client=client;
initRetrofit();
}
public static synchronized RetrofitManager getInstance(String baseUrl,OkHttpClient client){
if (mRetrofitManager == null){
mRetrofitManager = new RetrofitManager(baseUrl,client);
}
return mRetrofitManager;
}
private void initRetrofit() {
mRetrofit = new Retrofit.Builder()
.baseUrl(baseUrl)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.client(client)
.build();
}
public <T> T setCreate(Class<T> reqServer){
return mRetrofit.create(reqServer);
}
}
activity
public class ShowActivity extends AppCompatActivity implements Iview {
private Banner mBan;
List<String> list = new ArrayList<>();
private RecyclerView mRecy;
private VideoView videoView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//初始化 Fresco
Fresco.initialize(this);
setContentView(R.layout.activity_show);
//隐藏标题
ActionBar actionBar = getSupportActionBar();
actionBar.hide();
initView();
okUrlBanner();
MyPresenter presenter = new MyPresenter(this);
presenter.loadData();
}
private void initView() {
mBan = (Banner) findViewById(R.id.ban);
mRecy = (RecyclerView) findViewById(R.id.recy);
videoView= (VideoView) findViewById(R.id.video_view);
//创建布局管理器
LinearLayoutManager ll = new LinearLayoutManager(this);
mRecy.setLayoutManager(ll);
}
//Banner轮播
private void okUrlBanner() {
OkHttpUtils.getInstance().doGet(Api.BanUrl, new OnUiCallback() {
@Override
public void onFailed(Call call, IOException e) {
}
@Override
public void onSuccess(String result) throws IOException {
Gson gson = new Gson();
Beans beans = gson.fromJson(result, Beans.class);
for (int i = 0; i < beans.getData().size(); i++) {
list.add(beans.getData().get(i).getImage_url());
}
mBan.setImageLoader(new Img());
mBan.setImages(list);
mBan.start();
}
});
}
//请求数据
@Override
public void setData(List<Beans.DataBean> beanList) {
//创建适配器
ShowAdapter showAdapter = new ShowAdapter(ShowActivity.this, beanList);
mRecy.setAdapter(showAdapter);
//条目点击
showAdapter.setmOnItemClickListener(new ShowAdapter.OnItemClickListener() {
@Override
public void onItemClick(View view, int position) {
Toast.makeText(ShowActivity.this,"点击下载播放",Toast.LENGTH_SHORT).show();
DialogUtils.showUpdataDialog(ShowActivity.this);
DialogUtils.setPlay(new DialogUtils.autopPlay() {
@Override
public void autopplay(String path) {
//播放视频
Uri uri = Uri.parse(path);
videoView.setMediaController(new MediaController(ShowActivity.this));
videoView.setVideoURI(uri);
videoView.start();
videoView.requestFocus();
}
});
}
});
}
}
net_DownloadTask
public class DownloadTask extends Thread {
String downloadUrl;
String path;
int blockSize;
int startPosition;
public DownloadTask(String downloadUrl, String path, int blockSize, int startPosition) {
this.downloadUrl = downloadUrl;
this.path = path;
this.blockSize = blockSize;
this.startPosition = startPosition;
}
@Override
public void run() {
NetUtils.downloadFile(downloadUrl,path,blockSize,startPosition);
}
}
net_DownloadThread
public class DownloadThread extends Thread{
private String downloadUrl = "";
private String path;
private int threadNum = 4;
public DownloadThread(String downloadUrl, String path) {
this.downloadUrl = downloadUrl;
this.path = path;
}
@Override
public void run() {
int len = NetUtils.getFileLength(downloadUrl);
DialogUtils.MAX_SIZE = len;
//例如 1000kb 3 333
int blockSize = len/threadNum;
// //四舍五入--- 让一个数字+0。5在四舍五入 就变成 向上取整
// int blockSize = (int) Math.round(tempSize + 0.5);
//计算出下载块以后 创建线程执行下载操作
for (int i = 0; i < threadNum; i++) {
//计算开始位置
int startPosition = blockSize * i;
//让最后一个线程下载的大小是正好的, 总长度 - 除了最后一个块的大小和
if(i == threadNum - 1){
blockSize = len - blockSize * (threadNum - 1);
}
new DownloadTask(downloadUrl, path, blockSize, startPosition).start();
}
}
public void setThreadNum(int threadNum){
this.threadNum = threadNum;
}
}
net_NetUtils
public class NetUtils {
public static void downloadFile(String downloadUrl, String path, int blockSize, int startPosition){
BufferedInputStream bis = null;
RandomAccessFile raf = null;
try {
File f = new File(path);
if(!f.exists()){
f.createNewFile();
}
URL url = new URL(downloadUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(8000);
conn.setConnectTimeout(8000);
// long start = 0;
if(blockSize > 0){
// //使用线程id来计算 当前线程的开始位置和结束位置
// start = blockSize * threadId;
long end = blockSize + startPosition - 1;
//多线程下载 需要告诉服务器我要请求的是哪部分内容 需要写在请求头里面
conn.setRequestProperty("Range", "bytes=" + startPosition + "-" + end);
Log.i(Thread.currentThread() + "======", "bytes=" + startPosition + "-" + end);
}
int code = conn.getResponseCode();
if(code < 400){
bis = new BufferedInputStream(conn.getInputStream());
raf = new RandomAccessFile(f, "rwd");
raf.seek(startPosition);
int len = 0;
byte[] buff = new byte[1024 * 8];
while((len = bis.read(buff)) != -1){
synchronized (NetUtils.class){
raf.write(buff, 0, len);
if ( DialogUtils.PROGRESS<0){
DialogUtils.PROGRESS = 0;
}
DialogUtils.PROGRESS += len;
}
}
}
} catch (Exception e) {
e.printStackTrace();
}finally {
if(bis != null){
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(raf != null){
try {
raf.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public static int getFileLength(String downloadUrl){
int len = 0;
try {
URL url = new URL(downloadUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(8000);
conn.setConnectTimeout(8000);
len = conn.getContentLength();
} catch (Exception e) {
e.printStackTrace();
}
return len;
}
}
网友评论