您的位置:首页 > 移动开发 > Android开发

android断点下载并显示进度,关于handler,和主线程不能联网采取子线程联网下载,和多线程下载学习

2015-08-11 09:33 489 查看
package cn.multidownload;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;

import connectservice.ConnectStream;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import android.os.Build;

public class MainActivity extends ActionBarActivity {
private EditText ed_address;
@SuppressWarnings("unused")
private Button bt_download;
private ProgressBar probar;
private TextView tv_v;
public  int totalsize;
private int cout=0;
public Handler handler=new Handler(){

@Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
Object pro=msg.obj;
if(pro instanceof Integer)
{
probar.setProgress((Integer) pro);
tv_v.setText("已完成:"+pro+"%");
}
if(pro instanceof String)
{
Toast.makeText(MainActivity.this, " 文件已存在", Toast.LENGTH_SHORT).show();
}
super.handleMessage(msg);
}

};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ed_address=(EditText) findViewById(R.id.ed_address);
bt_download=(Button) findViewById(R.id.bt_download);
probar=(ProgressBar) findViewById(R.id.progressBar1);
tv_v=(TextView) findViewById(R.id.tv_pro);
probar.setMax(100);

}

public void download(View v) throws FileNotFoundException
{
String st=ed_address.getText().toString();
if(st.equals(""))
{
Toast.makeText(this, "地址不能为空!", Toast.LENGTH_SHORT).show();
return;
}
Thread front=new Thread(new FrontDown());
try {
front.start();
front.join();

} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

int numberthread=3;

for(int id=1;id<=numberthread;id++)
{
new Thread(new Down(id,numberthread)).start();
}

}

class FrontDown implements Runnable
{

@Override
public void run() {
// TODO Auto-generated method stub
try{
String st=ed_address.getText().toString();
URL url=new URL(st);
HttpURLConnection con=(HttpURLConnection) url.openConnection();
con.setConnectTimeout(5000);
totalsize=con.getContentLength();
System.out.println(totalsize);
}catch(Exception e)
{
}
}

}

class Down implements Runnable
{
private int startposition;
private int endposition;
private int threadId;
private int numberofthread;

public Down(int threadId,int numberofthread)
{
this.threadId=threadId;
this.numberofthread=numberofthread;
}

public void setposition()
{
int blocksize=totalsize/numberofthread;
this.startposition=(threadId-1)*blocksize;
if(threadId==numberofthread)
this. endposition=totalsize;
else
this.endposition=this.startposition+blocksize-1;
}

public void run()
{
String address=ed_address.getText().toString();
int d=address.lastIndexOf("/");
String name=address.substring(d, address.length());
File f=new File(Environment.getDataDirectory(), name);

try {

setposition();
System.out.println(startposition+ "       "+endposition);
URL url=new URL(address);
HttpURLConnection con=(HttpURLConnection) url.openConnection();
con.setRequestProperty("Range", "bytes="+(this.startposition)+"-"+this.endposition);
con.setConnectTimeout(5000);
con.setRequestMethod("GET");
InputStream input=con.getInputStream();

RandomAccessFile output=new RandomAccessFile(f,"rwd");
output.seek(startposition);
int len=-1;
byte[] buf=new byte[1024];
while((len=input.read(buf))!=-1)
{
output.write(buf,0,len);
synchronized(MainActivity.class){
cout+=len;
Message  msg=new Message ();
msg.obj=(cout*100)/totalsize;
handler.sendMessage(msg);
}
}
output.close();
input.close();
System.out.println(threadId+"下载完成");

} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}
}

}


  xml文件

<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:android1="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffff00"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="cn.multidownload.MainActivity$PlaceholderFragment" >

<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:lines="2"
android:text="http://tomcat.apache.org/images/tomcat.png"
android:id="@+id/ed_address"/>

<Button
android:layout_below="@+id/ed_address"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Download:"
android:onClick="download"
android:id="@+id/bt_download"
/>

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/progressBar1"
android:text="已完成:"
android:textSize="10dp"
android:id="@+id/tv_pro"

/>
<ProgressBar
android1:id="@+id/progressBar1"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/bt_download"
android:layout_below="@+id/bt_download"
android:layout_marginLeft="20dp"
android:layout_marginTop="32dp" />

</RelativeLayout>


  其中清单文件一定要配置网络权限。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: