欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 新闻 > 社会 > Android 断点续传基础之单线程下载

Android 断点续传基础之单线程下载

2024/11/15 23:49:55 来源:https://blog.csdn.net/2401_85610425/article/details/139724140  浏览:    关键词:Android 断点续传基础之单线程下载

**遇到的问题:**在这因为返回值的问题烦躁了一下,有可能出现空指针的异常,已经提出成文章了

请参考http://blog.csdn.net/qq_27489007/article/details/53523378

文件关系图

断点续传流程图

开始撸代码(主要代码)

/**

  • 普通断点续传

*/

public class DuandianActivity extends AppCompatActivity {

@BindView(R.id.tv)

TextView tv;

@BindView(R.id.probar)

ProgressBar probar;

@BindView(R.id.btstar)

Button btstar;

@BindView(R.id.btstop)

Button btstop;

String url = “http://dldir1.qq.com/weixin/android/weixin6316android780.apk”;

private FileInfo fileInfo;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_duandian);

ButterKnife.bind(this);

probar.setMax(100);

//创建文件信息对象

fileInfo = new FileInfo(0, url, “文件名-下载进度”, 0, 0);

tv.setText(fileInfo.getFileName()); //设置显示下载的文件名

//注册广播接收器

IntentFilter filter = new IntentFilter();

filter.addAction(DownloadService.ACTION_UPDATE);

registerReceiver(mReceiver, filter);

}

//更新ui的广播接收器

BroadcastReceiver mReceiver = new BroadcastReceiver() {

@Override

public void onReceive(Context context, Intent intent) {

if (DownloadService.ACTION_UPDATE.equals(intent.getAction())) {

int finished = intent.getIntExtra(“finished”, 0);

probar.setProgress(finished);

if (probar.getProgress()==100){

Toast.makeText(DuandianActivity.this,“下载完成!”,Toast.LENGTH_SHORT).show();

}

}

}

};

//按钮事件监听

@OnClick({R.id.btstar, R.id.btstop})

public void onClick(View view) {

Intent intent = new Intent(DuandianActivity.this, DownloadService.class);

switch (view.getId()) {

case R.id.btstar:

//通过intent传递参数给service

intent.setAction(DownloadService.ACTION_START);

intent.putExtra(“fileInfo”, fileInfo);

Log.i(“TAG”,intent.getAction().toString());

startService(intent);

break;

case R.id.btstop:

intent.setAction(DownloadService.ACTION_STOP);

intent.putExtra(“fileInfo”, fileInfo);

startService(intent);

break;

}

}

@Override

protected void onDestroy() {

super.onDestroy();

if (mReceiver != null) {

unregisterReceiver(mReceiver);

}

}

}

DownloadService.java

/**

  • 下载的服务类

*/

public class DownloadService extends Service {

public static final String ACTION_START = “ACTION_START”;

public static final String ACTION_STOP = “ACTION_STOP”;

public static final String ACTION_UPDATE = “ACTION_UPDATE”;

public static final String DOWNLOAD_PATH = Environment.getExternalStorageDirectory().getAbsolutePath() + “/download”;//sd卡路径

private DownloadTask mDownloadTask = null;

@Override

public int onStartCommand(Intent intent, int flags, int startId) {

// Log.i(“TAG”, intent.getAction().toString());

// Log.i(“action”, intent.getAction().toString());

//获得activity传来的参数

if (ACTION_START.equals(intent.getAction())) {

FileInfo fileInfo = (FileInfo) intent.getSerializableExtra(“fileInfo”);

Log.i(“test”, “start” + fileInfo.toString());

//启动初始化线程

new InitThread(fileInfo).start();

} else if (ACTION_STOP.equals(intent.getAction())) {

FileInfo fileInfo = (FileInfo) intent.getSerializableExtra(“fileInfo”);

Log.i(“test”, “stop” + fileInfo.toString());

if (mDownloadTask != null) {

mDownloadTask.isPause = true;

Toast.makeText(getApplicationContext(),“暂停成功”,Toast.LENGTH_SHORT).show();

}else {

Toast.makeText(getApplicationContext(),“还未开始下载”,Toast.LENGTH_SHORT).show();

}

}

return super.onStartCommand(intent, Service.START_REDELIVER_INTENT, startId);

}

@Override

public IBinder onBind(Intent intent) {

return null;

}

private static final int MSG_INIT = 0;

Handler mhandler = new Handler() {

@Override

public void handleMessage(Message msg) {

super.handleMessage(msg);

switch (msg.what) {

case MSG_INIT:

FileInfo fileInfo = (FileInfo) msg.obj;

Log.i(“test”, “Init:” + fileInfo);

//启动下载任务

mDownloadTask = new DownloadTask(DownloadService.this, fileInfo);

mDownloadTask.download();

break;

}

}

};

/**

  • 子线程进行下载保存工作

  • 初始化子线程

*/

class InitThread extends Thread {

private FileInfo thread_fileInfo = null;

private RandomAccessFile raf;

public InitThread(FileInfo fileInfo) {

this.thread_fileInfo = fileInfo;

}

@Override

public void run() {

//连接网络文件

HttpURLConnection conn = null;

try {

URL url = new URL(thread_fileInfo.getUrl());

conn = (HttpURLConnection) url.openConnection();

conn.setRequestMethod(“GET”
);

conn.setConnectTimeout(3000);

int length = -1;

if (conn.getResponseCode() == 200) {

//获得文件长度

length = conn.getContentLength();

}

if (length <= 0) {

return;

}

File dir = new File(DOWNLOAD_PATH);

if (!dir.exists()) { //判断如果不存在则创建一个文件

dir.mkdir();

}

//在本地创建文件

File file = new File(dir, thread_fileInfo.getFileName());

//随机访问的文件 可以在文件的任意一个位置进行写入操作

//rwd可读可写可操作

raf = new RandomAccessFile(file, “rwd”);

//设置文件长度

raf.setLength(length);

thread_fileInfo.setLength(length);

mhandler.obtainMessage(MSG_INIT, thread_fileInfo).sendToTarget();

} catch (MalformedURLException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

} finally {

try {

if (conn != null && raf != null) {

raf.close(); //关闭文件操作

conn.disconnect(); //断掉链接

}

} catch (IOException e) {

e.printStackTrace();

}

}

super.run();

}

}

}

DownloadTask.java

/**

  • 下载的任务类 对文件的下载

  • Created by lung on 2016-12-07.

*/

public class DownloadTask {

private Context mContext = null;

private FileInfo mFileInfo = null;

private ThreadDAOImpl mThreadDAO = null;

private long mFinished = 0; //总的完成进度

public boolean isPause = false; //暂停下载的开关

public DownloadTask(Context mContext, FileInfo mFileInfo) {

this.mContext = mContext;

this.mFileInfo = mFileInfo;

mThreadDAO = new ThreadDAOImpl(mContext);

}

//下载的方法

public void download() {

//读取数据库的线程信息

List threaddInfos = mThreadDAO.getThreads(mFileInfo.getUrl());

TheardInfo info;

if (threaddInfos.size() == 0) { //如果数据库无线程信息

info = new TheardInfo(0, mFileInfo.getUrl(), 0, mFileInfo.getLength(), 0);

} else {

info = threaddInfos.get(0);//单线程的下载 所以使用get(0)

}

//创建子线程进行下载

new DownloadThread(info).start();

}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com