Multithreaded download instances in android

  • 2020-05-17 06:23:59
  • OfStack

 
public class MainActivity extends Activity { 
//  The statement controls  
//  Path and number of threads  
private EditText et_url, et_num; 
//  The progress bar  
public static ProgressBar pb_thread; 
//  Actions that show progress  
private TextView tv_pb; 
//  Number of threads  
public static int threadNum = 3; 
//  Each thread is responsible for the size of the download  
public int blockSize; 
public static int threadCount;//  The number of  
//  Access to the path 
public String path; 
public static boolean flag = true; 
//  Record the value of the progress bar  
public static int pb_count = 0; 
public static Handler handler; 
public static final int TEXTVALUE = 1; 
public static int pb_num = 0; 
public static int size = 0; 
@Override 
protected void onCreate(Bundle savedInstanceState) { 
super.onCreate(savedInstanceState); 
setContentView(R.layout.activity_main); 
et_url = (EditText) findViewById(R.id.et_path); 
et_num = (EditText) findViewById(R.id.et_threadNum); 
pb_thread = (ProgressBar) findViewById(R.id.pb_down); 
tv_pb = (TextView) findViewById(R.id.tv_pb); 
handler = new Handler() { 
@Override 
public void handleMessage(Message msg) { 
super.handleMessage(msg); 
switch (msg.what) { 
case TEXTVALUE: 
System.out.println("-----------------------" 
+ MainActivity.pb_count + "//////" 
+ MainActivity.size); 

//  change TEXTView 
pb_num = (MainActivity.pb_count * 100) / MainActivity.size; 
tv_pb.setText(" The current progress is +" + pb_num + "%"); 
break; 
default: 
break; 
} 
} 
}; 
} 
@Override 
public boolean onCreateOptionsMenu(Menu menu) { 
// Inflate the menu; this adds items to the action bar if it is present. 
// getMenuInflater().inflate(R.menu.down, menu); 
return true; 
} 
// Download operation  
public void downLoad(View v) { 
//  Change the variable value:  
MainActivity.flag = true; 
MainActivity.pb_count = 0; 
path = et_url.getText().toString(); 
String threadNum_et = et_num.getText().toString(); 
if (TextUtils.isEmpty(path) || TextUtils.isEmpty(threadNum_et)) { 
Toast.makeText(this, " Can't be empty ", Toast.LENGTH_LONG).show(); 
return; 
} 
Toast.makeText(this, "url:" + path + "--" + threadNum_et, 
Toast.LENGTH_LONG).show(); 
//  Convert to Numbers  
threadNum = Integer.valueOf(threadNum_et); 
new Thread(new Runnable() { 
@Override 
public void run() { 
try { 
//  To create a URL object  
URL url = new URL(path); 
//  To create a  HttpURLConnection object  
HttpURLConnection httpURLConnection = (HttpURLConnection) url 
.openConnection(); 
//  Set up the   The way a request is sent  
httpURLConnection.setRequestMethod("GET"); 
//  Sets whether the request is timed out  
httpURLConnection.setConnectTimeout(5000); 
//  Set up the  
httpURLConnection 
.setRequestProperty("User-Agent", 
" Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Trident/6.0)"); 
//  Whether the response is successful or not  
if (httpURLConnection.getResponseCode() == 200) { 
//  Gets the size of the file  
size = httpURLConnection.getContentLength(); 
System.out.println(" File size " + size); 
//  Set the maximum value of the progress bar  
pb_thread.setMax(size); 
//  Create a file  // Save to SD Card.  
//  First determine if you own it sdcard 
if (Environment.getExternalStorageState().equals( 
Environment.MEDIA_MOUNTED)) { 
//  To obtain sdCard File directory object  
File sdFile = Environment 
.getExternalStorageDirectory(); 
//  Create file object  
File file = new File(sdFile, "youdao.exe"); 
RandomAccessFile accessFile = new RandomAccessFile( 
file, "rwd"); 
//  Set the size of the file  
accessFile.setLength(size); 
//  Size of download per thread  
blockSize = size / threadNum; 
//  open 3 A thread   Manipulate this file  
for (int i = 1; i <= threadNum; i++) { 
// 1 2 3 
//  Calculate where each thread starts  
int startSize = (i - 1) * blockSize; 
//  End position  
int endSize = (i) * blockSize; 
//  When the thread is last 1 In threads  
if (i == threadNum) { 
//  Determine if the size of the file is greater than the calculated ending position  
if (size > endSize) { 
//  End position   Is equal to the   File size  
endSize = size; 
} 
} 
//  Create for each thread 1 A random read  
RandomAccessFile threadAccessFile = new RandomAccessFile( 
file, "rwd"); 
new Thread(new DownLoadThread(i, 
threadAccessFile, startSize, endSize, 
path)).start(); 
} 
} 
} 
} catch (MalformedURLException e) { 
// TODO Auto-generated catch block 
e.printStackTrace(); 
} catch (IOException e) { 
// TODO Auto-generated catch block 
e.printStackTrace(); 
} 
} 
}).start(); 
} 
// Suspend operations  
public void downPause(View v) { 
Toast.makeText(this, " suspended ", Toast.LENGTH_LONG).show(); 
this.flag = false; 
} 
} 

 
public class DownLoadThread implements Runnable { 
//  Download the package of the file  
public RandomAccessFile accessFile; 
//  Where the thread started to download the file  
public int startSize; 
public int endSize; 
//  File download path The path  
public String path; 
public int threadId; //  Thread identity  
public DownLoadThread(int threadId, RandomAccessFile accessFile, 
int startSize, int endSize, String path) { 
this.threadId = threadId; 
this.accessFile = accessFile; 
this.startSize = startSize; 
this.endSize = endSize; 
this.path = path; 
} 
@Override 
public void run() { 
//  perform run methods  
try { 
//  Create a file to SD Card up  
//  First determine if you own it sdcard 
if (Environment.getExternalStorageState().equals( 
Environment.MEDIA_MOUNTED)) { 
//  To obtain sdCard File directory object  
File sdFile = Environment.getExternalStorageDirectory(); 
File threadFile = new File(sdFile, threadId + ".txt"); 
if (threadFile.exists()) { 
//  Read the contents of the file  
//  Create an input stream object for the file  
FileInputStream fis = new FileInputStream(threadFile); 
//  Read by the utility class  
byte data[] = StreamTools.isToData(fis); 
//  Convert to a string  
String threadLen = new String(data); 
if ((threadLen != null) && (!"".equals(threadLen))) { 
startSize = Integer.valueOf(threadLen); 
//  To solve  416bug The error  
if (startSize > endSize) { 
startSize = endSize - 1; 
} 
} 
} 
//  Create a file  
//  create URL object  
URL url = new URL(path); 
//  create HttpURLConnection object  
HttpURLConnection httpURLConnection = (HttpURLConnection) url 
.openConnection(); 
//  Sets the header of the request  
httpURLConnection.setRequestMethod("GET"); 
//  Sets whether the request is timed out  
httpURLConnection.setConnectTimeout(5000); 
//  Set up the  
httpURLConnection 
.setRequestProperty("User-Agent", 
" Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Trident/6.0)"); 
//  Key Settings  
httpURLConnection.setRequestProperty("Range", "bytes=" 
+ startSize + "-" + endSize); 
//  Output current thread  
System.out.println(" The current thread " + threadId + "  Download start location :" + startSize 
+ "  End of download location :" + endSize); 
//  In response to success  
//  Set to read files randomly   The starting position  
accessFile.seek(startSize); 
//  Gets the corresponding flow object  
InputStream is = httpURLConnection.getInputStream(); 
//  Create an output stream object  
byte buffer[] = new byte[1024]; 
int len = 0; 
int threadTotal = 0;//  Each thread saves the record after downloading  / 
while ((len = is.read(buffer)) != -1) { 
accessFile.write(buffer, 0, len); 
threadTotal += len;//  Record the length of what you write  //xml file  
// Change the progress bar:  
setProgressBar(len); 
//  Record the length of the file download by file  
FileOutputStream fos = new FileOutputStream(threadFile); 
fos.write((threadTotal + "").getBytes()); 
fos.flush(); 
fos.close(); 
// send handler The message  
MainActivity.handler.sendEmptyMessage(MainActivity.TEXTVALUE); 
if(!MainActivity.flag){ 
return; 
} 
} 
accessFile.close(); 
is.close(); 
System.out.println(threadId + " Thread execution complete "); 
//  Thread operation  
synchronized (MainActivity.class) { 
MainActivity.threadCount++; 
if (MainActivity.threadCount >= MainActivity.threadNum) { 
for (int i = 1; i <= MainActivity.threadNum; i++) { 
//  To obtain sdCard The file on the  
File deleteFile = new File(sdFile, i + ".txt"); 
if (deleteFile.exists()) { 
//  File deletion  
deleteFile.delete(); 
} 
} 
} 
} 
} 
} catch (MalformedURLException e) { 
// TODO Auto-generated catch block 
e.printStackTrace(); 
} catch (IOException e) { 
// TODO Auto-generated catch block 
e.printStackTrace(); 
} 
} 



public synchronized void setProgressBar(int len){ 
MainActivity.pb_count+=len; 
MainActivity.pb_thread.setProgress(MainActivity.pb_count); 
} 



} 

 
public class StreamTools { 

public static byte[] isToData(InputStream is) throws IOException{ 
//  Byte output stream  
ByteArrayOutputStream bops = new ByteArrayOutputStream(); 
//  The cache where the data is read  
byte buffer[] = new byte[1024]; 
//  Read a record of length  
int len = 0; 
//  Loop reads  
while ((len = is.read(buffer)) != -1) { 
bops.write(buffer, 0, len); 
} 
//  Convert the read to byte An array of  
byte data[] = bops.toByteArray(); 

bops.flush(); 
bops.close(); 
is.close(); 
return data; 
} 
} 

Complete source code

Related articles: