2012-09-10 40 views
0

我想使用IntentService(从BroadcastReceiver开始)从Internet下载文件,但我想通知用户文件是否已成功下载,如果被下载来解析文件。在我的IntentService里面使用处理程序和handleMessage是一个很好的解决方案?从我读的IntentServices是简单的工作线程处理意图后过期,所以有可能处理程序不处理消息?在IntentService中使用Handler由BroadcastReceiver启动

private void downloadResource(final String source, final File destination) { 
    Thread fileDownload = new Thread(new Runnable() { 
     @Override 
     public void run() { 
      try { 
       URL url = new URL(source); 
       HttpURLConnection urlConnection = (HttpURLConnection) 
               url.openConnection(); 
       urlConnection.setRequestMethod("GET"); 
       urlConnection.setDoOutput(true); 
       urlConnection.connect(); 

       FileOutputStream fileOutput = new FileOutputStream(destination); 
       InputStream inputStream = urlConnection.getInputStream(); 

       byte[] buffer = new byte[1024]; 
       int bufferLength; 

       while ((bufferLength = inputStream.read(buffer)) > 0) { 
        fileOutput.write(buffer, 0, bufferLength); 
       } 
       fileOutput.close(); 

       // parse the downloaded file ? 
      } catch (Exception e) { 
       e.printStackTrace(); 
       destination.delete(); 
      } 
     } 
    }); 
    fileDownload.start(); 
} 

回答

1

如果你只是想创建一个通知,告知用户,那么你可以下载你IntentService后做(见Sending a notification from a service in Android

如果你想显示一个更加完备的UI(通过活动),那么你可能要开始与startActivity()方法,您的应用程序的活动之一(见android start activity from service

如果您不需要任何UI的东西,只是做在IntentService解析下载之后。

+0

我只是想解析下载的文件,没有任何UI交互。 – Paul

+0

噢,但你说“我想告诉用户文件是否被成功下载”。如果您不需要任何用户界面,为什么不在下载后将它解析到IntentService中? – fiddler

+0

我在帖子中添加了一些代码。所以可以在行解析文件“//解析下载的文件?” ? – Paul

相关问题