我需要在我的应用程序中显示用户的图片,并且我从服务器检索该图片,因为我的应用程序也可以在离线模式下工作,所以我需要将该图片从服务器保存到我的SD卡,当我从服务器同步数据时也是如此下次如果图片已经改变,那么我还需要更改SD卡中的图片如何确定特定用户的图片是否已更改
目前我从服务器保存图像如下,但我现在使用硬编码网址和静态用户ID
public class fetchImage extends Activity implements OnClickListener {
int id;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
id = 1;// declaring static as of now
}
{
new BackgroundTask().execute();
File storagePath = Environment.getExternalStorageDirectory();
File imgFile = new File(storagePath, "/Pictures/" + id + ".jpg");
if (imgFile.exists()) {
Bitmap myBitmap = BitmapFactory.decodeFile(imgFile
.getAbsolutePath());
}
}
class BackgroundTask extends AsyncTask<Void, Void, Void> {
ProgressDialog mDialog;
protected void onPreExecute() {
mDialog = ProgressDialog.show(fetchImage.this, "",
getString(R.string.progress_bar_loading), true);
};
@Override
protected Void doInBackground(Void... params) {
try {
savesd(id, null);
} catch (final Exception e) {
}
return null;
}
private void savesd(int id, URL uri) throws IOException {
URL url;
if (uri == null) {
url = new URL("http://i.zdnet.com/blogs/3-29-androids.jpg");
} else {
url = uri;
}
InputStream input = url.openStream();
try {
File storagePath = Environment.getExternalStorageDirectory();
OutputStream output = new FileOutputStream(new File(
storagePath, "/Pictures/" + id + ".jpg"));
try {
byte[] buffer = new byte[20000];
int bytesRead = 0;
while ((bytesRead = input.read(buffer, 0, buffer.length)) >= 0) {
output.write(buffer, 0, bytesRead);
}
} finally {
output.close();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
input.close();
}
}
protected void onPostExecute(Void result) {
mDialog.dismiss();
};
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
}
此外我还有一个问题,当我从设备上卸载此应用时,它也应该从SD卡清除这些用户图像
答案 0 :(得分:0)
我使用时间戳来节省上次同步数据和仅在该时间戳之后下载文件的时间