SoFunction
Updated on 2025-04-04

Android implements simple file download and upload

File download

/**
  * Download Service IntentService
  * life cycle:
  * 1>Android container when the IntentService is first started
  * An IntentService object will be created.
  * 2>IntentService will rotate the message queue in the worker thread.
  * Execute business logic in each message object.
  * 3>If there is still a message in the message queue, continue execution.
  * If the message in the message queue has been executed,
  * IntentService will be automatically destroyed and the onDestroy method will be executed.
  */
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 startService is called,
    * IntentService will put the OnHandlerIntent in
    * Business logic is placed in the message queue and waits for execution.
    * When the worker thread cycles to the message object, it will
    * Execute this method.
    */
  protected void onHandleIntent(Intent intent) {
    //Send Http request to execute download service    //1. Get the path to music    String url=("url");
    String bit=("bit");
    String title=("title");
    //2. Build a File object to save music files    // /mnt/sdcard/Music/_64/Song title.mp3    File targetFile = new File((Environment.DIRECTORY_MUSIC),"_"+bit+"/"+title+".mp3" );         
    if(()){
      ("info", "Music already exists");
      return;
    }
    if(!().exists()){
      ().mkdirs();
    }
    try {
      sendNotification("Music Start Download", "Music Start Download");
      //3. Send Http request and get InputStream      InputStream is = (url);
      //4. Save to File object while reading      FileOutputStream fos = new FileOutputStream(targetFile);
      byte[] buffer = new byte[1024*100];
      int length=0;
      int current = 0;
      int total = (("total"));
      while((length=(buffer)) != -1){
        (buffer, 0, length);
        ();
        current += length;
        //Notify the progress of download        double progress = (1000.0*current/total)/10;
        sendNotification("Music Start Download", "Download progress:"+progress+"%");
      }
      //5. File download is completed      ();
      cancelNotification(); //The scrolling message appears again      sendNotification("Music download completed", "Music download completed");
    } catch (Exception e) {
      ();
    }
  }
  /**
    * Send a notice
    */
  public void sendNotification(String ticker, String text){
    NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
     builder = new (this);
    (.ic_launcher)
      .setContentTitle("Music Download")
      .setContentText(text)
      .setTicker(ticker);
    Notification n = ();
    (NOTIFICATION_ID, n);
  }
  /**
    * Cancel notification
    */
  public void cancelNotification(){
    NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    (NOTIFICATION_ID);
  }    
}

File upload

 /**
    * Upload file
    * @param uploadFile
    */ 
  private void uploadFile(final File uploadFile) { 
    new Thread(new Runnable() {      
      @Override 
      public void run() { 
        try { 
          ((int)()); 
          String souceid = (uploadFile); 
          String head = "Content-Length="+ () + ";filename="+ () + ";source" : souceid)+"\r\n"; 
          Socket socket = new Socket("192.168.1.78",7878); 
          OutputStream outStream = (); 
          (()); 
          PushbackInputStream inStream = new PushbackInputStream(());   
          String response = (inStream); 
          String[] items = (";"); 
          String responseid = items[0].substring(items[0].indexOf("=")+1); 
          String position = items[1].substring(items[1].indexOf("=")+1); 
          if(souceid==null){//It means that this file has not been uploaded, and add a binding record to the database            (responseid, uploadFile); 
          } 
          RandomAccessFile fileOutStream = new RandomAccessFile(uploadFile, "r"); 
          ((position)); 
          byte[] buffer = new byte[1024]; 
          int len = -1; 
          int length = (position); 
          while(start&&(len = (buffer)) != -1){ 
            (buffer, 0, len); 
            length += len; 
            Message msg = new Message(); 
            ().putInt("size", length); 
            (msg); 
          } 
          (); 
          (); 
          (); 
          (); 
          if(length==()) (uploadFile); 
        } catch (Exception e) { 
          (); 
        } 
      } 
    }).start(); 
  } 
} 

Summarize

The above is the entire content of this article. I hope that the content of this article has certain reference value for your study or work. Thank you for your support. If you want to know more about it, please see the relevant links below