How to Implement multi‑thread breakpoint download in Android

Source: Internet
Author: User

How to Implement multi‑thread breakpoint download in Android

This example describes how to implement multi‑thread breakpoint download in Android. Share it with you for your reference. The specific implementation method is as follows:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

140

141

142

143

144

145

146

147

148

149

150

151

152

153

154

155

156

157

158

159

160

161

162

163

164

165

166

167

168

169

170

171

172

173

174

175

176

177

178

179

180

181

182

183

184

185

186

187

188

189

190

191

192

193

194

195

196

197

198

199

200

201

202

203

204

205

206

207

208

209

210

211

212

213

214

215

216

217

Package cn. itcast. download;

Import java. io. File;

Import java. io. FileInputStream;

Import java. io. FileNotFoundException;

Import java. io. FileOutputStream;

Import java. io. IOException;

Import java. io. InputStream;

Import java. io. RandomAccessFile;

Import java.net. HttpURLConnection;

Import java.net. MalformedURLException;

Import java.net. ProtocolException;

Import java.net. URL;

Import cn. itcast. mutiledownload. StreamTool;

Import android. app. Activity;

Import android. OS. Bundle;

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. TextView;

Import android. widget. Toast;

Public class MutiledownloadActivity extends Activity implements OnClickListener {

Private ProgressBar pb;

Private Button bt;

Private TextView TV;

Private EditText et;

Boolean flag = true;

Boolean stopflag = false;

Private Handler handler = new Handler (){

@ Override

Public void handleMessage (Message msg ){

Pb. setProgress (total );

Int max = pb. getMax ();

If (total> = (max-1 )){

Total = max;

Flag = false;

}

Int result = total * 100/max;

TV. setText ("current progress:" + result + "% ");

Super. handleMessage (msg );

}

};

Int total = 0;

@ Override

Public void onCreate (Bundle savedInstanceState ){

Super. onCreate (savedInstanceState );

SetContentView (R. layout. main );

Pb = (ProgressBar) this. findViewById (R. id. pb );

Bt = (Button) this. findViewById (R. id. bt );

TV = (TextView) this. findViewById (R. id. TV _process );

Et = (EditText) this. findViewById (R. id. et );

Bt. setOnClickListener (this );

}

@ Override

Public void onClick (View v ){

Switch (v. getId ()){

Case R. id. bt:

// Create a subthread to regularly update the ui

If ("start to download". equals (bt. getText (). toString ())){

Bt. setText ("paused ");

Stopflag = false; // start download

}

Else {

Bt. setText ("START download ");

Stopflag = true;

}

New Thread (){

@ Override

Public void run (){

Super. run ();

While (flag ){

Try {

Sleep (1000 );

// If total> = file length

Message msg = new Message ();

Handler. sendMessage (msg );

} Catch (InterruptedException e ){

E. printStackTrace ();

}

}

}

}. Start ();

 

// Start the download operation

String path = et. getText (). toString (). trim ();

If ("". equals (path )){

Toast. makeText (this, "path cannot be blank", 1). show ();

Return;

}

Try {

URL url = new URL (path );

HttpURLConnection conn = (HttpURLConnection) url

. OpenConnection ();

Conn. setRequestMethod ("GET ");

Conn. setConnectTimeout (5000 );

Conn. setRequestProperty ("User-Agent ",

"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1 )");

Int code = conn. getResponseCode ();

If (code = 200 ){

Int len = conn. getContentLength ();

RandomAccessFile file = new RandomAccessFile (

"/Mnt/sdcard/" + getFilenName (path), "rwd ");

// 1. Set the local file size to the same as the Server File Size

File. setLength (len );

// Set the maximum value of the progress bar

Pb. setMax (len );

// 2. Assume that three threads are enabled.

Int threadnumber = 3;

Int blocksize = len/threadnumber;

/**

* Thread 1 0 ~ Blocksize thread 2 1 * bolocksize ~ 2 * blocksize thread 3

* 2 * blocksize ~ End of File

*/

For (int I = 0; I <threadnumber; I ++ ){

Int startposition = I * blocksize;

Int endpositon = (I + 1) * blocksize;

If (I = (threadnumber-1 )){

// The last thread

Endpositon = len;

}

DownLoadTask task = new DownLoadTask (I, path,

Startposition, endpositon );

Task. start ();

}

}

} Catch (Exception e ){

Toast. makeText (this, "Download exception", 0). show ();

E. printStackTrace ();

}

Break;

}

}

Class DownLoadTask extends Thread {

Int threadid;

String filepath;

Int startposition;

Int endpositon;

Public DownLoadTask (int threadid, String filepath, int startposition,

Int endpositon ){

This. threadid = threadid;

This. filepath = filepath;

This. startposition = startposition;

This. endpositon = endpositon;

}

@ Override

Public void run (){

Try {

File postionfile = new File ("/mnt/sdcard/" + threadid + ". txt ");

URL url = new URL (filepath );

HttpURLConnection conn = (HttpURLConnection) url

. OpenConnection ();

System. out. println ("Thread" + threadid + "downloading" + "start position :"

+ Startposition + "end position" + endpositon );

If (postionfile. exists ()){

FileInputStream FCM = new FileInputStream (postionfile );

Byte [] result = StreamTool. getBytes (SOx );

String str = new String (result );

If (! "". Equals (str )){

Int newstartposition = Integer. parseInt (str );

If (newstartposition> startposition ){

Startposition = newstartposition;

}

}

}

// "Range", "bytes = 2097152-4194303 ")

Conn. setRequestProperty ("Range", "bytes =" + startposition + "-"

+ Endpositon );

Conn. setRequestMethod ("GET ");

Conn. setConnectTimeout (5000 );

Conn. setRequestProperty ("User-Agent ",

"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1 )");

InputStream is = conn. getInputStream ();

RandomAccessFile file = new RandomAccessFile ("/mnt/sdcard /"

+ GetFilenName (filepath), "rwd ");

// Set the position where the data is written from the file

File. seek (startposition );

Byte [] buffer = new byte [1024];

Int len = 0;

// Represents the location of the server data currently read, and the location of the file with this value already stored

Int currentPostion = startposition;

// Create a file object to record the download location of the current file

While (len = is. read (buffer ))! =-1 ){

If (stopflag ){

Return;

}

File. write (buffer, 0, len );

Synchronized (MutiledownloadActivity. this ){

Total + = len;

}

CurrentPostion + = len;

// The currentPostion information needs to be persistently stored on the storage device.

String position = currentPostion + "";

FileOutputStream fos = new FileOutputStream (postionfile );

Fos. write (position. getBytes ());

Fos. flush ();

Fos. close ();

}

File. close ();

System. out. println ("Thread" + threadid + "download completed ");

// Delete the object after the thread download is complete.

If (postionfile. exists ()){

Postionfile. delete ();

}

} Catch (Exception e ){

E. printStackTrace ();

}

Super. run ();

}

}

Public String getFilenName (String path ){

Int start = path. lastIndexOf ("/") + 1;

Return path. substring (start, path. length ());

}

}

I hope this article will help you design your Android program.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.