Search code examples
androidftpandroid-asynctaskalarmmanager

Is different thread needed for this application?


I have an app that periodically downloads a very small text file (10 bytes) via FTP, then uploads a larger one (200-ish bytes). It does this using alarm manager, and seems to work well. I'm wondering if I need to run it on a different thread, in case the internet becomes congested, or am I being over cautious? Here's the code for the FTP download:

 public void getFTP(Context context)
 {
  //
  // Download config.txt file from server
  //
   FTPClient ftpClient = new FTPClient();

 try{

 ftpClient.connect(InetAddress.getByName(ipAddress));  
 ftpClient.enterLocalPassiveMode();
 ftpClient.login("user", "pass");
 ftpClient.setFileType(FTP.ASCII_FILE_TYPE);

 BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("/sdcard/config.txt"),8*1024);

 boolean status=ftpClient.retrieveFile("config.txt", bos);

 if(status){
     Toast toast = Toast.makeText(context, "Downloaded config.txt!", Toast.LENGTH_SHORT);
     toast.show();
     }
     else {
     Toast toast = Toast.makeText(context, "Cannot download config.txt!", Toast.LENGTH_SHORT);
     toast.show();  
     return;
     }

 bos.flush();
 bos.close();

 ftpClient.logout();
 ftpClient.disconnect();

 }

 catch (IOException e){
     Toast.makeText(context,"Connection error!" , Toast.LENGTH_LONG).show();
 return;
 }

Solution

  • If the question is "Should I make network connection in non-UI thread, even if they are small" - than the answer is Yes, for sure.

    Because starting from ICS, for example, Android will prohibit network connections from UI thread and will throw the exception if you will try.

    Besides, it's just a very good practice to separate all possibly-long tasks to another threads. And 'long' I think is > 300ms (Android will start to push warnings in logs if any Handler's method will be longer than 300ms, for example).

    Note: If you will start async operation inside on AlarmManager callback - be ready that system may "sleep" and hibernate, even if you'd told AlarmManager to wake up for event. You can read about this behavior here: http://developer.android.com/reference/android/app/AlarmManager.html in the top header, paragraph 2.

    Good luck