断点续传 和 单例

mac2024-10-16  50

@[toc] 断点续传 和 单例

断点续传

activity

package com.example.day01_homework; 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.view.View; import android.widget.AdapterView; import android.widget.ImageView; import android.widget.ListView; import android.widget.ProgressBar; import android.widget.Toast; import java.io.File; import java.util.ArrayList; import java.util.List; public class MainActivity extends AppCompatActivity { private ListView listView; private ProgressBar progressList; private MyAdapter adapter; private String path = "http://www.qubaobei.com/ios/cf/dish_list.php?stage_id=1&limit=20&page=1"; private List<Food.DataBean> list = new ArrayList<>(); private String url = "/storage/emulated/0/Pictures/"; public static long all = 0; private String path1 = ""; private Handler handler = new Handler() { @Override public void handleMessage(Message msg) { super.handleMessage(msg); if (msg.what == 120) { int len = (int) msg.obj; progressList.setProgress(len); if (len == 100) { progressList.setVisibility(View.GONE); Toast.makeText(MainActivity.this, "下载完成", Toast.LENGTH_SHORT).show(); } } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE}, 110); } initview(); loadFromNet(); } private void loadFromNet() { new MyAsynctask(list, adapter).execute(path); } private void initview() { listView = (ListView) findViewById(R.id.list_view); progressList = (ProgressBar) findViewById(R.id.progress_list); adapter = new MyAdapter(list, this); listView.setAdapter(adapter); listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, final int position, long id) { path1 = url + position + ".jpg"; File file = new File(path1); if (file.exists()) { Toast.makeText(MainActivity.this, "图片已存在", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(MainActivity.this, "图片不存在", Toast.LENGTH_SHORT).show(); AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this); builder.setTitle("友情提示!"); builder.setMessage("是否下载该图片"); builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }); builder.setPositiveButton("Allow", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { progressList.setVisibility(View.VISIBLE); String pic = list.get(position).getPic(); new MyThread(pic, path1, handler).start(); } }); AlertDialog dialog = builder.create(); dialog.show(); } } }); } }

子线程

package com.example.day01_homework; 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; class MyThread extends Thread { private String str_url; private String path; private Handler handler; public MyThread(String str_url, String path, Handler handler) { this.str_url = str_url; this.path = path; this.handler = handler; } private long end; private long start; @Override public void run() { super.run(); try { URL url = new URL(str_url); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setReadTimeout(3 * 1000); connection.setConnectTimeout(3 * 1000); connection.connect(); if (connection.getResponseCode() == 200) { //获取总长度 end = connection.getContentLength(); // MainActivity.all = end; Log.d("TAG", "end: " + end); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } //第二次 设置请求头 File file = new File(path); if (file.exists()) { start = file.length(); } else { start = 0; } Log.d("TAG", "start: " + start); try { URL url = new URL(str_url); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setReadTimeout(3 * 1000); connection.setConnectTimeout(3 * 1000); connection.setRequestProperty("Range", "bytes=" + start + "-" + end); connection.connect(); if (connection.getResponseCode() == 206) { InputStream inputStream = connection.getInputStream(); RandomAccessFile randomAccessFile = new RandomAccessFile(path, "rw"); randomAccessFile.seek(start); int len = 0; byte[] bytes = new byte[1024]; long count = start; while ((len = inputStream.read(bytes)) != -1) { randomAccessFile.write(bytes, 0, len); count += len; int progress = (int) ((count * 100) / end); Log.d("TAG", "run: " + progress); Message obtain = Message.obtain(); obtain.what = 120; obtain.obj = progress; handler.sendMessage(obtain); } } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }

单例 懒汉

package com.example.day01_homework; public class TestUtils2 { private TestUtils2() { } private static TestUtils2 testUtils2 = null; public static TestUtils2 getInstance() { if (testUtils2 == null) { synchronized (Object.class) { if (testUtils2 == null) { testUtils2 = new TestUtils2(); } } } return testUtils2; } } package com.example.day01_homework; public class Teest02 { public void test() { TestUtils2 instance1 = TestUtils2.getInstance(); TestUtils2 instance2 = TestUtils2.getInstance(); if (instance1.equals(instance2)) { System.out.println("1346789"); } else { System.out.println("987654321"); } } }

饿汉

package com.example.day01_homework; public class TestUtils { private TestUtils() { } private static TestUtils testUtils = new TestUtils(); public static TestUtils getInstance() { return testUtils; } } package com.example.day01_homework; public class single_e { public void getTest() { TestUtils utils1 = TestUtils.getInstance(); TestUtils utils2 = TestUtils.getInstance(); if (utils1.equals(utils2)) { System.out.println("1346789"); } else { System.out.println("987654321"); } } }

总结

断点续传 就是在下载的过程中给数据加上一个标记,就是从本地的缓存中读取已下载的部分,然后在网络请求中加上一个请求头,来从服务端请求数据,只请求未下载的部分。

单例 懒汉 懒汉式就是在开始的时候不去创建对象,而是在后面进行创建,但是这个会有线程安全的问题,在这里就需要用到双重校验锁,就是一个同步锁里面嵌套一个判断,判断对象是否已存在,如果已存在就复用。

而饿汉就是在一开始就创建出对象,这样就不会产生线程安全问题,但是这样会比较下号资源。

最新回复(0)