我有这些代码来获取Bing当天的照片并将其设置为background.it工作正常,但我有一些感觉,这不是最佳方式。
获取json并返回字符串:
private String GetHTTPData() {
try {
URL url = new URL(urlString);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
if (urlConnection.getResponseCode() == 200) {
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
BufferedReader r = new BufferedReader(new InputStreamReader(in));
StringBuilder sb = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
sb.append(line);
}
stream = sb.toString();
urlConnection.disconnect();
} else {
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
}
if (stream != null) {
try {
JSONObject jsonObject = new JSONObject(stream);
JSONArray jArray = jsonObject.getJSONArray("images");
for (int i = 0; i < jArray.length(); i++) {
JSONObject jsonobject = jArray.getJSONObject(i);
imageURL = "http://www.bing.com" + jsonobject.getString("url");
}
} catch (Exception e) {
e.printStackTrace();
}
}
//I replaced the original resolution with mine to change the image url
imageURL=imageURL.replace("1920x1080","1080x1920");
return imageURL;
}
图片的默认值是1920x1080,我可以通过更换尺寸获得更多手机友好的图像,但我不确定1080x1920是否是最好的。
然后我的AsyncTask
private class setWallpaper extends AsyncTask<Void,Void,Bitmap>{
@Override
protected Bitmap doInBackground(Void... strings) {
int response=-1;
InputStream in=null;
Bitmap bitmap=null;
String stream=GetHTTPData();
try {
URL url = new URL(stream);
URLConnection connection =url.openConnection();
HttpURLConnection urlConnection=(HttpURLConnection)connection;
urlConnection.setAllowUserInteraction(false);
urlConnection.setInstanceFollowRedirects(true);
urlConnection.setRequestMethod("GET");
urlConnection.connect();
response=urlConnection.getResponseCode();
if (response==HttpURLConnection.HTTP_OK){
in=urlConnection.getInputStream();
}
bitmap= BitmapFactory.decodeStream(in);
in.close();
}catch (Exception e){
return null;
}
//I dont like to scale my bitmap but on lower resolution i cant get full width image
WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int width = size.x;
int height = size.y;
Bitmap bitmapTouse=Bitmap.createScaledBitmap(bitmap,width,height,true);
bitmap.recycle();
return bitmapTouse;
}
@Override
protected void onPostExecute(Bitmap bitmap) {
System.gc();
WallpaperManager manager=WallpaperManager.getInstance(context.getApplicationContext());
try {
manager.setBitmap(bitmap);
Log.d("SUCCESS----", "Finished");
} catch (IOException e) {
Log.d("FAILED----",e.getMessage());
}
}
}
我也不想缩放我的位图图片,但我不得不这样做。