Android 在由BroadcastReceiver启动的IntentService中使用处理程序
我想使用Android 在由BroadcastReceiver启动的IntentService中使用处理程序,android,handler,Android,Handler,我想使用IntentService(从BroadcastReceiver启动)从Internet下载文件,但我想通知用户文件下载是否成功,以及是否下载以解析文件。在我的IntentService中使用处理程序和handleMessage是一个好的解决方案吗?从我读到的IntentServices是处理intent后过期的简单工作线程,那么处理程序是否可能不处理消息 private void downloadResource(final String source, final File dest
IntentService
(从BroadcastReceiver
启动)从Internet下载文件,但我想通知用户文件下载是否成功,以及是否下载以解析文件。在我的IntentService
中使用处理程序和handleMessage
是一个好的解决方案吗?从我读到的IntentServices
是处理intent后过期的简单工作线程,那么处理程序是否可能不处理消息
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();
}
如果您只想创建通知以通知用户,则可以在下载到您的IntentService后执行(请参阅) 如果您希望(通过活动)显示更精细的UI,则可能需要使用startActivity()方法启动应用程序的一个活动(请参阅)
如果您不需要任何UI内容,请在下载后立即在
IntentService
中进行解析。我只想解析下载的文件,不需要任何UI交互。哦,好的,但您说“我想通知用户文件下载成功与否”。如果您不需要任何UI,为什么不在下载后在IntentService中解析它呢?我在帖子中添加了一些代码。所以可以在“//解析下载的文件”行解析文件吗?当然可以。为什么不呢?只要你的解析能修改任何用户界面的东西,我会在几分钟内尝试一下。