매일 한 번 씩 - Bing 매일 한 그림 을 가 져 와 안 드 로 이 드 환영 페이지 구현 (2)
12059 단어 매일 한 번
두 번 째 부분: bing 일 일 그림 가 져 오기
방문 을 통 해 http://www.bing.com/HPImageArchive.aspx?format=js&idx=0&n=5&mkt=zh-CN json 데 이 터 를 얻 을 수 있 습 니 다. 다음 과 같 습 니 다.
{"images":
[{"startdate":"20180911",
"fullstartdate":"201809111600",
"enddate":"20180912",
"url":"/az/hprichbg/rb/BlackBrowed_ZH-CN11903207028_1920x1080.jpg",
"urlbase":"/az/hprichbg/rb/BlackBrowed_ZH-CN11903207028",
"copyright":" (© Cultura RM/Alamy)",
"copyrightlink":"http://www.bing.com/search?q=%E9%BB%91%E7%9C%89%E4%BF%A1%E5%A4%A9%E7%BF%81&form=hpcapt&mkt=zh-cn",
"title":"",
"quiz":"/search?q=Bing+homepage+quiz&filters=WQOskey:%22HPQuiz_20180911_BlackBrowed%22&FORM=HPQUIZ",
"wp":true,
"hsh":"12948b177d0c26492dcb1049700602ea",
"drk":1,"top":1,"bot":1,"hs":[]},
{"startdate":"20180910",
"fullstartdate":"201809101600",
"enddate":"20180911",
"url":"/az/hprichbg/rb/ShinjukuKiku_ZH-CN8446848393_1920x1080.jpg",
"urlbase":"/az/hprichbg/rb/ShinjukuKiku_ZH-CN8446848393",
"copyright":" , (© I love Photo and Apple./Getty images)",
"copyrightlink":"http://www.bing.com/search?q=%E7%AE%A1%E7%89%A9%E8%8F%8A&form=hpcapt&mkt=zh-cn",
"title":"","quiz":"/search?q=Bing+homepage+quiz&filters=WQOskey:%22HPQuiz_20180910_ShinjukuKiku%22&FORM=HPQUIZ",
"wp":true,
"hsh":"c79ceca8823a08c1c93373f4b26c9996",
"drk":1,"top":1,"bot":1,"hs":[]},
{"startdate":"20180909",
"fullstartdate":"201809091600",
"enddate":"20180910",
"url":"/az/hprichbg/rb/Honeycomb_ZH-CN7204448210_1920x1080.jpg",
"urlbase":"/az/hprichbg/rb/Honeycomb_ZH-CN7204448210",
"copyright":" (© Heidi and Hans-Juergen Koch/Minden Pictures)",
"copyrightlink":"http://www.bing.com/search?q=%E8%9C%82%E5%B7%A2&form=hpcapt&mkt=zh-cn",
"title":"",
"quiz":"/search?q=Bing+homepage+quiz&filters=WQOskey:%22HPQuiz_20180909_Honeycomb%22&FORM=HPQUIZ",
"wp":true,
"hsh":"956060a94d566e18964ea6aff9a7a2aa",
"drk":1,"top":1,"bot":1,"hs":[]},
{"startdate":"20180908",
"fullstartdate":"201809081600",
"enddate":"20180909",
"url":"/az/hprichbg/rb/RoyalOntarioMuseum_ZH-CN10362892998_1920x1080.jpg",
"urlbase":"/az/hprichbg/rb/RoyalOntarioMuseum_ZH-CN10362892998",
"copyright":" , (© Ken Straiton/Aurora Photos)",
"copyrightlink":"http://www.bing.com/search?q=%E7%9A%87%E5%AE%B6%E5%AE%89%E5%A4%A7%E7%95%A5%E5%8D%9A%E7%89%A9%E9%A6%86&form=hpcapt&mkt=zh-cn",
"title":"",
"quiz":"/search?q=Bing+homepage+quiz&filters=WQOskey:%22HPQuiz_20180908_RoyalOntarioMuseum%22&FORM=HPQUIZ",
"wp":false,
"hsh":"ed4c961d60ff9e9ebc17f94a4fa5e8cb",
"drk":1,"top":1,"bot":1,"hs":[]},
{"startdate":"20180907",
"fullstartdate":"201809071600",
"enddate":"20180908",
"url":"/az/hprichbg/rb/TrinityLibrary_ZH-CN10332583093_1920x1080.jpg",
"urlbase":"/az/hprichbg/rb/TrinityLibrary_ZH-CN10332583093",
"copyright":" , (© Nigel Hicks/Robert Harding/Aurora Photos)",
"copyrightlink":"http://www.bing.com/search?q=%E4%B8%89%E4%B8%80%E5%AD%A6%E9%99%A2%E5%9B%BE%E4%B9%A6%E9%A6%86&form=hpcapt&mkt=zh-cn",
"title":"",
"quiz":"/search?q=Bing+homepage+quiz&filters=WQOskey:%22HPQuiz_20180907_TrinityLibrary%22&FORM=HPQUIZ",
"wp":false,
"hsh":"e5b5bf66170be8116ecd6a6f73fb1e1e",
"drk":1,"top":1,"bot":1,"hs":[]}],
"tooltips":{
"loading":" ...",
"previous":" ",
"next":" ",
"walle":" 。",
"walls":" 。 。"}}
JSON 데이터 가 나 오 는 걸 봤 어 요. 각 그룹 에 하나의 url 속성 이 있 습 니 다. 즉, "url": "/ az / hprichbg / rb / BlackBrowed ZH - CN1193207028 1920 x1080. jpg" 입 니 다. 우 리 는 이 URL 을 통 해 현재 이 그룹의 그림 을 얻 을 수 있 습 니 다. 주의해 야 할 것 은 이 URL 은 사이트 의 앞부분 이 부족 하고 방문 할 때 추가 해 야 합 니 다. "http://www.bing.com", 즉 사이트 주 소 는:http://www.bing.com/az/hprichbg/rb/BlackBrowed_ZH-CN11903207028_1920x1080.jpg。그러면 필요 한 논리 코드 를 알 수 있 습 니 다. 첫 번 째 단 계 는 이 JSON 데 이 터 를 얻 는 것 입 니 다.두 번 째 단 계 는 이 JSON 데 이 터 를 분석 하 는 것 입 니 다.세 번 째 단 계 는 얻 은 그림 URL 을 bitmap 로 바 꾸 는 것 입 니 다.네 번 째 단 계 는 전 환 된 bitmap 를 배경 그림 에 할당 하고 이 bitmap 를 로 컬 에 저장 하 는 것 입 니 다. 프로그램 을 다시 열 때 로 컬 그림 에 직접 접근 할 수 있 습 니 다. 중복 다운로드 하지 않 아 도 됩 니 다.
STEP 1: JSON 데이터 가 져 오기
여기 서 제 가 사용 하 는 링크 는 HttpURLConnection 입 니 다. 코드 는 다음 과 같 습 니 다.
private String getData(String path){
String data="";
try{
URL url = new URL(path);
HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
urlConn.setConnectTimeout(5000);
urlConn.connect();
if (urlConn.getResponseCode() == 200) {
data = readStream(urlConn.getInputStream());
Log.i("TAG", " ");
} else {
Log.i("TAG", " ");
}
urlConn.disconnect();
}catch (Exception e){
e.printStackTrace();
}
return data;
}
private String readStream(InputStream inputStream) throws IOException {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len;
while ((len = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, len);
outputStream.flush();
}
outputStream.close();
inputStream.close();
return outputStream.toString();
}
두 번 째 단계: JSON 데 이 터 를 분석 하여 이미지 URL 얻 기
이전에 얻 은 JSON 데 이 터 를 살 펴 보면 알 수 있 듯 이 이 데이터 에는 여러 개의 URL 이 포함 되 어 있 습 니 다. 즉, 여러 날짜 의 그림 이 존재 하고 우리 가 원 하 는 것 은 당일 날짜 의 그림 입 니 다. 따라서 관찰 해 보면 첫 번 째 URL 은 최신 그림 이 고 첫 번 째 URL 데 이 터 를 얻 었 을 때 이 URL 을 되 돌려 주면 됩 니 다.다른 URL 을 판단 할 필요 가 없습니다. 코드 는 다음 과 같 습 니 다.
private String resolveData(String data){
String url="";
try{
JSONArray jsonArray=new JSONObject(data).getJSONArray("images");
for (int i=0;i
세 번 째 단계: 그림 URL 을 bitmap 로 변환 합 니 다.
URL 앞 에 붙 여 주세요. "http://www.bing.com"코드 는 다음 과 같 습 니 다. (여기 서 문제 가 하나 있 습 니 다. 현재 해결 되 지 않 았 습 니 다. 어떤 고수 가 지적 해 주 었 습 니까? 바로 이 BitmapFactory. decodeStream () 에서 얻 은 그림 이 변형 되 었 습 니 다. 화면 에 적응 하고 변형 되 지 않 는 방법 을 어떻게 얻 습 니까?)
private Bitmap getBitmap(String path) throws IOException {
URL url = new URL("http://www.bing.com"+path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5000);
conn.setRequestMethod("GET");
if (conn.getResponseCode() == 200) {
InputStream inputStream = conn.getInputStream();
DisplayMetrics dm = getResources().getDisplayMetrics();//
Bitmap bitmap = Bitmap.createScaledBitmap(BitmapFactory.decodeStream(inputStream), dm.widthPixels, dm.heightPixels, true);
conn.disconnect();
return bitmap;
}
conn.disconnect();
return null;
}
네 번 째 단계: 배경 그림 에 값 을 부여 하고 bitmap 를 로 컬 에 저장 합 니 다.
이 단 계 는 그림 을 가 져 오 는 것 입 니 다. 따라서 앞의 세 단계 의 모든 함 수 를 호출 해 야 합 니 다. 따라서 특히 주의해 야 할 것 은 Android 4.0 이후 네트워크 에 관 한 모든 작업 이 메 인 스 레 드 에 있 을 수 없습니다. (우리 가 bing 을 방문 할 때 INTERNET 권한 을 사 용 했 습 니 다) 여기 서 AsyncTask 를 사 용 했 습 니 다.또한 로 컬 에 그림 이 없어 서 그림 을 불 러 올 때 네트워크 속도 에 따라 인터페이스의 기다 림 을 초래 할 수 있 기 때문에 ProgressDialog 를 추 가 했 습 니 다. 구체 적 인 코드 는 다음 과 같 습 니 다.
class DownImgAsyncTask extends AsyncTask {
@Override
protected Bitmap doInBackground(String... strings) {
try{
Bitmap b=getBitmap(resolveData(getData(strings[0])));
return b;
}catch (IOException e){
e.printStackTrace();
}
return null;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog.show();
}
@Override
protected void onPostExecute(Bitmap bitmap) {
super.onPostExecute(bitmap);
if (bitmap!=null){
iv_background.setImageBitmap(bitmap);
//
CutPictureUtils.saveImageToGallery(SplashActivity.this,bitmap);
}
progressDialog.dismiss();
}
@Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
}
로 컬 에 저 장 된 함수 코드 는 다음 과 같 습 니 다.
public static void saveImageToGallery(Context context, Bitmap bmp) {
//
File appDir = new File(Environment.getExternalStorageDirectory(), "crazystudy");
if (!appDir.exists()) {
appDir.mkdir();
}
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy MM dd ");// HH:mm:ss
//
Date date = new Date(System.currentTimeMillis());
String fileName = simpleDateFormat.format(date) + ".jpg";
File file = new File(appDir, fileName);
try {
FileOutputStream fos = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// //
// try {
// MediaStore.Images.Media.insertImage(context.getContentResolver(),
// file.getAbsolutePath(), fileName, null);
// } catch (FileNotFoundException e) {
// e.printStackTrace();
// }
// //
// context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + file.getPath())));
}
이제 우 리 는 이 DownImgAsyncTask 를 호출 하여 환영 페이지 의 제작 을 완성 할 수 있 습 니 다. 에서 "bing 배경 그림 가 져 오기" 의 예약 위 치 를 설정 하고 다음 코드 를 추가 할 수 있 습 니 다.
if(AnalysisUtils.isFolderExists("/sdcard/crazystudy/")){
if (AnalysisUtils.fileIsExists(imgUri.getPath())){
//
CutPictureUtils cutPictureUtils=new CutPictureUtils(SplashActivity.this,
"");
iv_background.setImageBitmap(cutPictureUtils.decodeUriAsBitmap(imgUri));
}else {
progressDialog = new ProgressDialog(this);
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.setMessage(" ");
progressDialog.setCancelable(false);
//
String path = "http://www.bing.com/HPImageArchive.aspx?format=js&idx=0&n=5&mkt=zh-CN";
new DownImgAsyncTask().execute(path);
}
}
이렇게 환영 페이지 를 완벽 하 게 만 들 었 습 니 다. 다음은 효과 그림 입 니 다.