单例模式 断点续传

这篇博客探讨了单例模式的饿汉式和懒汉式实现,并详细讲解了断点续传技术,涉及布局设计、item布局、网络请求、JavaBean类的编写、适配器应用以及异步处理和线程操作。

单例模式(饿汉式和懒汉式)

package com.example.app2;

public class Utils {
    //饿汉式
//    public Utils() {
//    }
//    private  static Utils utils = new Utils();
//    public static Utils getInstance(){
//        return utils;
//    }

    //懒汉式
    public Utils() {
    }
    private static Utils utils = null;
    public static Utils getInstance(){

        if (utils == null){
            synchronized (Object.class){
                if (utils == null){
                     utils = new Utils();
                }
            }
        }
        return utils;
    }
}

断点续传

布局

<?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=".MainActivity">

    <ListView
        android:id="@+id/lv"
        android:layout_width="match_parent"
        android:layout_height="match_parent"></ListView>

    <SeekBar
        android:id="@+id/bar"
        android:layout_width="match_parent"
        android:layout_height="20sp"
        android:layout_centerInParent="true"
        android:visibility="gone"/>

</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">
                <ImageView
                    android:id="@+id/zz"
                    android:layout_width="100dp"
                    android:layout_height="100dp"
                    android:src="@mipmap/ic_launcher"
                    android:layout_centerInParent="true"/>
</RelativeLayout>

网络请求

package com.example.day1031;

import android.util.Log;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

public class Httputils {
    private static final String TAG = "Httputils";
    public static String geturl(String s){
        try {
            URL url = new URL(s);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.connect();
            Log.i(TAG, "geturl: "+connection.getResponseCode());
            if (connection.getResponseCode() == 200){
                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                InputStream inputStream = connection.getInputStream();
                int len = 0;
                byte[] bytes = new byte[1024];
                while ((len = inputStream.read(bytes))!=-1){
                    byteArrayOutputStream.write(bytes,0,len);
                }
                return  byteArrayOutputStream.toString();
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {


        }
        return null;
    }
}

写一个JavaBean的类

适配器

package com.example.day1031;

import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;

import com.bumptech.glide.Glide;

import java.util.List;

public class MyAdapter extends BaseAdapter {
    private static final String TAG = "MyAdapter";
    private List<JavaBean.DataBean> list;
    private Context context;
    private LayoutInflater layoutInflater;

    public MyAdapter(List<JavaBean.DataBean> list, Context context) {
        this.list = list;
        this.context = context;
        layoutInflater = LayoutInflater.from(context);
    }

    @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) {
        ViewHolder holder = null;
        if (convertView == null){
            holder = new ViewHolder();
            convertView = layoutInflater.inflate(R.layout.layout_item,null);
            holder.iv = convertView.findViewById(R.id.zz);
            convertView.setTag(holder);
        }else {
            holder = (ViewHolder) convertView.getTag();
        }
        Glide.with(context).load(list.get(position).getPic()).into(holder.iv);
        return convertView;
    }
    class  ViewHolder{
        ImageView iv;
    }
}

异步

package com.example.day1031;

import android.os.AsyncTask;
import android.util.Log;

import com.google.gson.Gson;

import java.util.List;

public class MyAsync extends AsyncTask<String,Void, List<JavaBean.DataBean>> {

    private static final String TAG = "MyAsync";
    private List<JavaBean.DataBean> list ;
    private MyAdapter myAdapter;

    public MyAsync(List<JavaBean.DataBean> list, MyAdapter myAdapter) {
        this.list = list;
        this.myAdapter = myAdapter;
    }

    @Override
    protected List<JavaBean.DataBean> doInBackground(String... strings) {
        String geturl = Httputils.geturl(strings[0]);
        Log.i(TAG, "doInBackground: "+geturl);
        if (geturl != null){
            JavaBean javaBean = new Gson().fromJson(geturl, JavaBean.class);
            List<JavaBean.DataBean> data = javaBean.getData();
            return data;
        }
        return null;
    }

    @Override
    protected void onPostExecute(List<JavaBean.DataBean> dataBeans) {
        super.onPostExecute(dataBeans);
        if (dataBeans != null){
            list.addAll(dataBeans);
            myAdapter.notifyDataSetChanged();
            Log.i(TAG, "onPostExecute: "+list.get(1).getTitle());
        }
    }
}

Thread

package com.example.day1031;

import android.os.Handler;
import android.os.Message;
import android.util.Log;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;


public class MyThread extends  Thread {
    private static final String TAG = "MyThread";
    private String url ;
    private String path;
    private Handler handler;

    public MyThread(String url, String path, Handler handler) {
        this.url = url;
        this.path = path;
        this.handler = handler;
    }

    private long start = 0;
    private long end;
    @Override
    public void run() {

        //第一次请求
        try {
            URL url = new URL(this.url);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.connect();
            Log.i(TAG, "run: "+connection.getResponseCode());
            if (connection.getResponseCode() == 200){
                end = connection.getContentLength();
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        File file = new File(path);
        if (file.exists()){
            start = file.length();
        }else {
            start = 0;
        }

        //第二次请求
        try {
            URL url = new URL(this.url);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.connect();
            Log.i(TAG, "run: "+connection.getResponseCode());
            if (connection.getResponseCode() == 200){
                if (start == end){
                    handler.sendEmptyMessage(200);
                }else{
                    InputStream inputStream = connection.getInputStream();
                    RandomAccessFile rw = new RandomAccessFile(path, "rw");
                    rw.seek(start);
                    long context = start;
                    int len = 0;
                    byte[] bytes = new byte[1024];
                    while ((len = inputStream.read(bytes))!=-1){
                        rw.write(bytes,0,len);

                        context+=len;

                        int progress = (int) (context*100/end);

                        Message message = new Message();
                        message.what = 100;
                        message.arg1 = progress;
                        handler.sendMessage(message);
                    }
                }
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Main

package com.example.day1031;

import android.Manifest;
import android.content.DialogInterface;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SeekBar;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {


    private static final String TAG = "MainActivity";
    private ListView lv;
    private SeekBar bar;



    private List<JavaBean.DataBean> list = new ArrayList<>();
    private String url="http://www.qubaobei.com/ios/cf/dish_list.php?stage_id=1&limit=10&page=1";

    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 100){
                bar.setVisibility(View.VISIBLE);
                int arg1 = msg.arg1;
                bar.setProgress(arg1);
                if (arg1 == bar.getMax()){
                    bar.setVisibility(View.GONE);
                }
            }
            if (msg.what == 200){
                Toast.makeText(MainActivity.this, "已经下载", Toast.LENGTH_SHORT).show();
            }
        }
    };
    private MyAdapter myAdapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        lv = (ListView) findViewById(R.id.lv);
        bar = (SeekBar) findViewById(R.id.bar);

        //获取权限
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
            requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},100);
        }

        //设置适配器
        myAdapter = new MyAdapter(list,this);
        lv.setAdapter(myAdapter);

        //进行异步
        Async();

        //设置点击事件
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
                AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                builder.setTitle("提示");
                builder.setMessage("是否下载这张图片");
                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                            new MyThread(list.get(position).getPic(),"/storage/emulated/0/Movies/"+"pic"+position+".jpg",handler).start();
                    }
                });
                builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Toast.makeText(MainActivity.this, "取消", Toast.LENGTH_SHORT).show();
                    }
                });
                AlertDialog alertDialog = builder.create();
                alertDialog.show();
            }
        });
    }

    private void Async() {
        new MyAsync(list,myAdapter).execute(url);
    }
}

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值