Android中级篇之多线程下载

本文介绍了一种基于Android平台的多线程下载方案。利用RandomAccessFile类实现了文件的任意位置写入,通过分割文件并分配给不同线程进行下载,提高了下载效率。文章还提供了完整的代码示例,包括下载工具类和下载活动类。

Android中级篇之多线程下载

2011-06-05 15:50:49

要是先多线程下载,则必须对同一个文件可任意位置的写入 ,java中提供这样一个类可任意写入RandomAccessFile 。通过多线程,可将文件分割成多个子断,每一个线程只需下载一段文件即可。实现效果如图:



下面看代码部分:

1.布局文件 main.xml

<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="下载路径" /> <EditText android:id="@+id/mEditText" android:layout_width="fill_parent" android:layout_height="wrap_content" android:singleLine="true" android:text="http://android.yesky.com/uploads/attachments/2010-04/27/a5964152.jpg"/> <ProgressBar android:id="@+id/mBar" android:layout_width="fill_parent" android:layout_height="wrap_content" android:visibility="invisible" style="?android:attr/progressBarStyleHorizontal"/> <Button android:id="@+id/mButton" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="下载"/> </LinearLayout>



2.下载工具类 Download.java

package com.yin.downloader.utils; 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 android.content.Context; import android.util.Log; public class Download { private String SDPath = null; private static final String TAG = "com.yin.download"; private RandomAccessFile randomFile = null; private URL url; private Context context; private String urlStr; private String fileName; private int fileSize; private int totalReadSize; public Download(String urlStr,String fileName,String SDPath,Context context){ this.context = context; this.fileName = fileName; this.urlStr = urlStr; this.SDPath = SDPath; } public void downloadFile(){ try { File file = new File(SDPath+fileName); url = new URL(urlStr); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); //获得下载文件的大小 fileSize = conn.getContentLength(); //设置线程的大小,考虑手机的性能,并不是越大越好 int threadSize = 3; //每个线程下载文件+的部分大小 +1 避免文件下载不完全 int block = fileSize / threadSize +1; for(int i=0;i<3;i++){ int startPosition = i * block; //创建可任意位置读取的文件 randomFile = new RandomAccessFile(file, "rw"); randomFile.seek(startPosition); new DownloadThread(i+1, startPosition, block, randomFile).start(); } } catch (MalformedURLException e) { Log.e(TAG, "MalformedURLException"); e.printStackTrace(); } catch (IOException e) { Log.e(TAG, "IOException"); e.printStackTrace(); } } //下载文件的线程 private class DownloadThread extends Thread{ private int threadID; private int startPosition; private int block; private RandomAccessFile randomFile; public DownloadThread(int threadID, int startPosition, int block, RandomAccessFile randomFile) { super(); this.threadID = threadID; this.startPosition = startPosition; this.block = block; this.randomFile = randomFile; } public void run() { try { HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); //文件下载位置 规定的格式 “byte=xxxx-” String start = "bytes="+startPosition + "-"; //设置文件开始的下载位置 conn.setRequestProperty("Range", start); InputStream is = conn.getInputStream(); byte[] buffer = new byte[4*1024]; int len = -1; int readFileSize = 0; while((readFileSize < block) && ((len = is.read(buffer)) != -1)){ randomFile.write(buffer,0,len); readFileSize += len ; totalReadSize += readFileSize; } System.out.println("线程 :"+threadID+" 下载完成"); is.close(); randomFile.close(); conn.disconnect(); } catch (IOException e) { Log.e(TAG+":child", "IOException"); e.printStackTrace(); } } } public int getFileSize() { return fileSize; } public void setFileSize(int fileSize) { this.fileSize = fileSize; } public int getTotalReadSize() { return totalReadSize; } public void setTotalReadSize(int totalReadSize) { this.totalReadSize = totalReadSize; } }


3.DownloadActivity.java

package com.yin.downloader; import java.util.Timer; import java.util.TimerTask; import android.app.Activity; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.os.Message; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.ProgressBar; import android.widget.Toast; import com.yin.downloader.utils.Download; public class DownloadActivity extends Activity { public EditText mEditText; public ProgressBar mBar; public Button mButton; public String urlStr; public String fileName; public String SDPath = "/sdcard/"; public int fileSize; public int totalReadSize; Download download; public Handler handler = new Handler(){ @Override public void handleMessage(Message msg) { mBar.setProgress(download.getTotalReadSize()); mBar.invalidate(); } }; public Timer mTimer = new Timer(); public TimerTask mTask = new TimerTask() { @Override public void run() { Message msg = new Message(); handler.sendMessage(msg); } }; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); mEditText = (EditText) findViewById(R.id.mEditText); mBar = (ProgressBar) findViewById(R.id.mBar); mButton = (Button) findViewById(R.id.mButton); mButton.setOnClickListener(new ClickEven()); fileName = "my.jpg"; //判断SDcard是否存在。 if(Environment.getExternalStorageState() == Environment.MEDIA_MOUNTED){ SDPath ="/sdcard/"; }else{ Toast.makeText(this, "SDcard不存在", Toast.LENGTH_LONG).show(); } } private class ClickEven implements OnClickListener{ public void onClick(View v) { urlStr = mEditText.getText().toString(); mBar.setVisibility(View.VISIBLE); download = new Download(urlStr,fileName,SDPath,DownloadActivity.this); download.downloadFile(); //将progressbar的大小设置为下载文件大小 mBar.setMax(download.getFileSize()); //定时刷新 mTimer.schedule(mTask, 0, 200); } } }

此例实现比较简单,还可以加入断点续传的功能,把程序停止时当前线程现在的位置存入数据库中,再次下载时从数据库中取出即可;

Python 中集成 Ollama 可以通过使用 `ollama` 官方提供的 Python 客户端库来实现。Ollama 是一个本地运行的大型语言模型(LLM)工具,它支持多种模型,如 Llama 2、Mistral 等,并且可以通过简单的 APIPython 应用程序集成。 ### 安装 Ollama Python 库 首先,需要确保你已经在本地系统上安装了 Ollama。你可以从 [Ollama 官方网站](https://ollama.com/)下载并安装适用于你操作系统的版本。 接下来,安装 Python 客户端库。Ollama 提供了一个官方的 Python 包,可以通过 `pip` 安装: ```bash pip install ollama ``` ### 使用 Ollama Python 库 安装完成后,可以使用 `ollama` 模块来调用 OllamaAPI。以下是一个简单的示例,展示如何使用 Ollama 的 `generate` 方法来生成文本: ```python import ollama # 生成文本 response = ollama.generate(model='llama3', prompt='为什么天空是蓝色的?') # 打印响应 print(response['response']) ``` 在这个例子中,`model` 参数指定了要使用的模型(例如 `llama3`),`prompt` 参数是用户输入的提示词。Ollama 会根据提示词生成相应的文本,并返回一个包含 `response` 字段的字典。 ### 获取模型列表 如果你想查看当前可用的模型,可以使用以下代码: ```python import ollama # 获取模型列表 models = ollama.list() # 打印模型列表 for model in models['models']: print(model['name']) ``` ### 模型对话(Chat) Ollama 还支持更复杂的对话模式,允许你在多轮对话中保持上下文。以下是一个使用 `chat` 方法的示例: ```python import ollama # 开始对话 response = ollama.chat( model='llama3', messages=[ {'role': 'user', 'content': '你好,你能帮我做什么?'}, {'role': 'assistant', 'content': '你好!我可以帮助你回答问题、提供建议,甚至进行简单的创作。有什么我可以帮你的吗?'}, {'role': 'user', 'content': '你能告诉我关于机器学习的基础知识吗?'} ] ) # 打印响应 print(response['message']['content']) ``` 在这个例子中,`messages` 参数是一个包含多个对话记录的列表,每个记录都有一个 `role` 和 `content` 字段。Ollama 会根据这些对话记录生成相应的回复。 ### 错误处理 在实际应用中,建议添加错误处理逻辑,以应对可能出现的网络问题或模型加载失败等情况: ```python import ollama try: response = ollama.generate(model='llama3', prompt='为什么天空是蓝色的?') print(response['response']) except Exception as e: print(f"发生错误: {e}") ``` ### 相关问题
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值