我通过服务下载了许多png文件,现在我正在尝试使用它们。它们会进入用户的SD卡。我已经确认每个文件都在卡上。但是当我尝试将它们中的任何一个设置为ImageView时,我得到了空白区域。
所以,然后我通过手动尝试使用手机的图片浏览器在手机上显示文件,看到文件完好无损。这些文件都不会打开。我想知道的是,在下载需要发生的文件之后我是否缺少任何步骤,以使它们可以作为png文件(或位图文件)查看。以下是我用于下载文件的服务中的代码:
public class DownloadPicture extends IntentService {
private int result = Activity.RESULT_CANCELED;
public static final String FILENAME = "filename";
public static final String FILEPATH = "filepath";
public static final String RESULT = "result";
public static final String NOTIFICATION "com.mydomain.myapp.MyBroadcastReceiver";
public DownloadPicture() {
super("DownloadPicture");
}
public DownloadPicture(String name) {
super(name);
}
@Override
protected void onHandleIntent(Intent intent) {
String fileName = intent.getStringExtra(FILENAME);
String urlPath = this.getResources().getString(R.string.imagesURL) + fileName;
System.err.println("starting download of: " + fileName);
System.err.println(urlPath);
File output = new File(Environment.getExternalStorageDirectory(), fileName);
if (output.exists()) {output.delete();}
InputStream stream = null;
FileOutputStream fos = null;
try {
URL url = new URL(urlPath);
stream = url.openConnection().getInputStream();
InputStreamReader reader = new InputStreamReader(stream);
fos = new FileOutputStream(output.getPath());
int next = -1;
while ((next = reader.read()) != -1) {
fos.write(next);
}
//Maybe I need to do something else here????
// Successful finished
result = Activity.RESULT_OK;
} catch (Exception e) {
e.printStackTrace();
} finally {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
publishResults(output.getName(), output.getAbsolutePath(), result);
}
}
答案 0 :(得分:1)
不要使用InputStreamReader
它会将字节流转换为字符流。
http://docs.oracle.com/javase/6/docs/api/java/io/InputStreamReader.html
在你的情况下,图像必须保留字节流,这样你就可以使用InputStream
对象返回的URL
:
while ((next = stream.read()) != -1) {
fos.write(next);
}