Android Realizes Simple File Download and Upload
- 2021-10-27 08:45:35
- OfStack
File download
/**
* Download service IntentService
* Life cycle:
* 1> When the first 1 Secondary startup IntentService When, Android Container
* Will create IntentService Object.
* 2>IntentService Will round through the message queue in the worker thread,
* Execute the business logic in each message object.
* 3> If there are still messages in the message queue,
* If the message in the message queue has finished executing,
* IntentService Will automatically destroy, execute onDestroy Method.
*/
public class DownloadService extends IntentService{
private static final int NOTIFICATION_ID = 100;
public DownloadService(){
super("download");
}
public DownloadService(String name) {
super(name);
}
/**
* The code in this method will be executed in the worker thread
* Whenever you call startService Start IntentService After that,
* IntentService Will put OnHandlerIntent In
* Business logic is placed in a message queue to be executed.
* When the worker thread rounds to the message object, the
* Execute the method.
*/
protected void onHandleIntent(Intent intent) {
// Send Http Request Execute download service
//1. Get the path of music
String url=intent.getStringExtra("url");
String bit=intent.getStringExtra("bit");
String title=intent.getStringExtra("title");
//2. Build File Object for saving music files
// /mnt/sdcard/Music/_64/ Song title .mp3
File targetFile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC),"_"+bit+"/"+title+".mp3" );
if(targetFile.exists()){
Log.i("info", " Music already exists ");
return;
}
if(!targetFile.getParentFile().exists()){
targetFile.getParentFile().mkdirs();
}
try {
sendNotification(" Music begins to download ", " Music begins to download ");
//3. Send Http Request, get InputStream
InputStream is = HttpUtils.getInputStream(url);
//4. Save while reading to File Object
FileOutputStream fos = new FileOutputStream(targetFile);
byte[] buffer = new byte[1024*100];
int length=0;
int current = 0;
int total = Integer.parseInt(intent.getStringExtra("total"));
while((length=is.read(buffer)) != -1){
fos.write(buffer, 0, length);
fos.flush();
current += length;
// Notify the progress of the download
double progress = Math.floor(1000.0*current/total)/10;
sendNotification(" Music begins to download ", " Download progress: "+progress+"%");
}
//5. File download complete
fos.close();
cancelNotification(); // Scroll message reappears
sendNotification(" Music download complete ", " Music download finished ");
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Send a notice
*/
public void sendNotification(String ticker, String text){
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Notification.Builder builder = new Notification.Builder(this);
builder.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle(" Music download ")
.setContentText(text)
.setTicker(ticker);
Notification n = builder.build();
manager.notify(NOTIFICATION_ID, n);
}
/**
* Cancellation notice
*/
public void cancelNotification(){
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
manager.cancel(NOTIFICATION_ID);
}
}
File upload
/**
* Upload a file
* @param uploadFile
*/
private void uploadFile(final File uploadFile) {
new Thread(new Runnable() {
@Override
public void run() {
try {
uploadbar.setMax((int)uploadFile.length());
String souceid = logService.getBindId(uploadFile);
String head = "Content-Length="+ uploadFile.length() + ";filename="+ uploadFile.getName() + ";sourceid="+
(souceid==null? "" : souceid)+"\r\n";
Socket socket = new Socket("192.168.1.78",7878);
OutputStream outStream = socket.getOutputStream();
outStream.write(head.getBytes());
PushbackInputStream inStream = new PushbackInputStream(socket.getInputStream());
String response = StreamTool.readLine(inStream);
String[] items = response.split(";");
String responseid = items[0].substring(items[0].indexOf("=")+1);
String position = items[1].substring(items[1].indexOf("=")+1);
if(souceid==null){// To represent that this file has not been uploaded before, add it to the database 1 Bar binding record
logService.save(responseid, uploadFile);
}
RandomAccessFile fileOutStream = new RandomAccessFile(uploadFile, "r");
fileOutStream.seek(Integer.valueOf(position));
byte[] buffer = new byte[1024];
int len = -1;
int length = Integer.valueOf(position);
while(start&&(len = fileOutStream.read(buffer)) != -1){
outStream.write(buffer, 0, len);
length += len;
Message msg = new Message();
msg.getData().putInt("size", length);
handler.sendMessage(msg);
}
fileOutStream.close();
outStream.close();
inStream.close();
socket.close();
if(length==uploadFile.length()) logService.delete(uploadFile);
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
}
Summarize