32
Developing Android Apps 2.Connect Sunshine to the Cloud 시온고등학교 안드로이드 스터디

2.Connect Sunshine to the Cloud - 시온고 안드로이드 스터디

Embed Size (px)

Citation preview

Page 1: 2.Connect Sunshine to the Cloud - 시온고 안드로이드 스터디

Developing Android Apps2.Connect Sunshine to the Cloud

시온고등학교 안드로이드 스터디

Page 2: 2.Connect Sunshine to the Cloud - 시온고 안드로이드 스터디

GOALs :● HTTP Request 만들기

● Logging 하기 & Logcat 보기● Multithreading● Overflow Menu

● Permission 추가하기● JSON Parsing

Page 3: 2.Connect Sunshine to the Cloud - 시온고 안드로이드 스터디

http://openweathermap.org/apiOpenWeatherMap API 둘러보기

Page 4: 2.Connect Sunshine to the Cloud - 시온고 안드로이드 스터디

날씨 데이터 얻을 URL 정하기● id : 도시 id 값● units : 단위(metric - 섭씨, imperial - 화씨)

예시 - 부천지역날씨섭씨로 :http://api.openweathermap.org/data/2.5/forecast?id=1838716&units=metric

Page 5: 2.Connect Sunshine to the Cloud - 시온고 안드로이드 스터디

HttpURLConnection웹에 요청을 보내서 데이터를 보내거나 받기 위해서 사용됨.

Page 6: 2.Connect Sunshine to the Cloud - 시온고 안드로이드 스터디

날씨 데이터 얻기 …// 새 연결 열기

URL url = new URL("http://api.openweathermap.org/data/2.5/weather?id=1838716&units=metric"); HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

Page 7: 2.Connect Sunshine to the Cloud - 시온고 안드로이드 스터디

날씨 데이터 얻기 …

//InpurStream 얻고, 연결 끊기 try { InputStream in = new BufferedInputStream(urlConnection.getInputStream()); readStream(in);

catch(Exception e){} finally {

urlConnection.disconnect(); } }…

Page 8: 2.Connect Sunshine to the Cloud - 시온고 안드로이드 스터디

Log● 뭐긴 뭐야 로그 찍는 거지● 말 그대로 로그 찍어주는 코드● Error(오류), Warn(경고), Info(정보), Debug(디버그), Verbose(자세한 정보) 형태로 로그 찍기 가능.

Page 9: 2.Connect Sunshine to the Cloud - 시온고 안드로이드 스터디

LogLog.e(“로그", " 오류 발생");Log.w(“로그", "경고!");Log.i(“로그", " 새로운 정보!");Log.d(“로그", " 디버깅 결과");Log.v(“로그", " 더 자세한 정보");

Page 10: 2.Connect Sunshine to the Cloud - 시온고 안드로이드 스터디

오류 로그 찍기 … try { InputStream in = new BufferedInputStream(urlConnection.getInputStream()); readStream(in);

catch(Exception e){Log.e(“TAG”, “ 오류 발생! :" + e);

} finally {urlConnection.disconnect(); } }…

Page 11: 2.Connect Sunshine to the Cloud - 시온고 안드로이드 스터디

InputStream → StringString forecastJsonStr = null;…// Read the input stream into a String InputStream inputStream = urlConnection.getInputStream(); StringBuffer buffer = new StringBuffer(); if (inputStream == null) { // Nothing to do. forecastJsonStr = null; } reader = new BufferedReader(new InputStreamReader(inputStream));

String line; while ((line = reader.readLine()) != null) { // Since it's JSON, adding a newline isn't necessary (it won't affect parsing) // But it does make debugging a *lot* easier if you print out the completed // buffer for debugging. buffer.append(line + "\n"); }

if (buffer.length() == 0) { // Stream was empty. No point in parsing. forecastJsonStr = null; } forecastJsonStr = buffer.toString();

Page 12: 2.Connect Sunshine to the Cloud - 시온고 안드로이드 스터디

Thread● 하나의 프로그램 또는 프로세스 안에 실행되는 흐름의 단위.● 필요에 따라 여러 Thread를 실행 수 있음(Multithread)

Page 13: 2.Connect Sunshine to the Cloud - 시온고 안드로이드 스터디

UI Thread( 또는 Main Thread)

Background Thread

새로 Thread 만들고 실행UI에 접근하기 위해 요청

● 사용자에 의한 입출력을 처리● 시간 소모하는 작업 회피

시간을 소모하는 작업(예를 들면 네트워킹) 수행

Page 14: 2.Connect Sunshine to the Cloud - 시온고 안드로이드 스터디

AsyncTask오래 걸리는 작업을 쉽게 백그라운드 에서 처리 하도록 도와주는 클래스

Page 15: 2.Connect Sunshine to the Cloud - 시온고 안드로이드 스터디

private class myAsyncTask extends AsyncTask< 실행시 받을 매개변수 타입, 진행 현황 변수 타입, 완료시 반환할 변수 타입> {

protected void onPreExecute() {// 백그라운드 작업 전에 Main Thread 에 실행 }

protected void doInBackground(Params... params) {// 백그라운드 작업 실행 }

protected void onProgressUpdate(Progress... progress) {// 도중에 진행 정도 변경 시 Main Thread 에서 실행 publishProgress(progress); }

protected void onPostExecute(Result result) {// 백그라운드 작업 후 실행 } }

Page 16: 2.Connect Sunshine to the Cloud - 시온고 안드로이드 스터디

Overflow Menu

Page 17: 2.Connect Sunshine to the Cloud - 시온고 안드로이드 스터디

Menu Item 정의하기<?xml version="1.0" encoding="utf-8"?><menu xmlns:android="http://schemas.android.com/apk/res/android"> <item android:id="@+id/settings" android:title="@string/help" />

<item android:id="@+id/refresh" android:title="@string/refresh" /></menu>

Page 18: 2.Connect Sunshine to the Cloud - 시온고 안드로이드 스터디

Menu를 Inflate 하기… @Overridepublic void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {inflater.inflate(R.menu.menu_main, menu);}…

Page 19: 2.Connect Sunshine to the Cloud - 시온고 안드로이드 스터디

Menu를 Inflate 하기… @Overridepublic boolean onOptionsItemSelected(MenuItem item) {

int id = item.getItemId();if (id == R.id.settings) {//settings 항목 선택 시 실행될 작업

return true;}

return super.onOptionsItemSelected(item);}…

Page 20: 2.Connect Sunshine to the Cloud - 시온고 안드로이드 스터디

Menu 가 Framgent 에있는것인가요?… //그렇다면, Menu 를 가지고 있다고 알려줍시다.setHasOptionsMenu(true);…

Page 21: 2.Connect Sunshine to the Cloud - 시온고 안드로이드 스터디

Permission(권한)● Android 에서는 모든 앱들이 별도의 각각의 샌드박스 라는 보호된 영역에서 실행되며, 기본적으로 다른 앱 이나 휴대전화에 저장된 데이터 등에 접근할 수 없음.● 다른 앱에 접근하거나, 저장된 개인 데이터 접근하는 등 민감한 작업을 때는, Manifest에 해당 Permission을 명시하여, 앱이 해당 Permission 필요로 하는 작업을 실행 함을 나타냄.

Page 22: 2.Connect Sunshine to the Cloud - 시온고 안드로이드 스터디

Manifest에 인터넷 사용 권한 정의하기<manifest

xmlns:android="http://schemas.android.com/apk/res/android"

package="com.example.android.sunshine.app" >

<uses-permission android:name="android.permission.INTERNET" />

<application android:allowBackup="true"…

Page 23: 2.Connect Sunshine to the Cloud - 시온고 안드로이드 스터디

JSON Parsing 을 통해 필요한 값 얻기1. 네트워킹을 통해 얻은 String 데이터를 JSONObject 로 변환2. 필요한 JSONObject 를 위에 변환한 JSONObject 에서 추출하기 3. 추출한 JSONObject 에서 값 얻기

Page 24: 2.Connect Sunshine to the Cloud - 시온고 안드로이드 스터디

String → JSONObject → JSONArray… //forecastJsonStr : 네트워킹으로 얻은 데이터

JSONObject forecastJson = new

JSONObject(forecastJsonStr);

JSONArray weatherArray =

forecastJson.getJSONArray("list”);…

Page 25: 2.Connect Sunshine to the Cloud - 시온고 안드로이드 스터디

추출, 값 얻기… String[] resultStrs = new String[numDays]; for(int i = 0; i < weatherArray.length(); i++) { JSONObject dayForecast = weatherArray.getJSONObject(i);

JSONObject weatherObject = dayForecast.getJSONArray(“weather”).getJSONObject(0); String description = weatherObject.getString(“main”);… }

Page 26: 2.Connect Sunshine to the Cloud - 시온고 안드로이드 스터디

Adapter 갱신하기… // 데이터 비우기myAdapter.clear();// 새로 작업한 데이터 추가myAdapter.addAll(newDataArray);…

Page 27: 2.Connect Sunshine to the Cloud - 시온고 안드로이드 스터디

관련 라이브러리 이용해 보기OkHttpIon

Page 28: 2.Connect Sunshine to the Cloud - 시온고 안드로이드 스터디

http://square.github.io/okhttp/ OkHttp

Page 29: 2.Connect Sunshine to the Cloud - 시온고 안드로이드 스터디

OkHttp 예제private final OkHttpClient client = new OkHttpClient();Request request = new Request.Builder() .url("http://api.openweathermap.org/…") .build(); client.newCall(request).enqueue(new Callback() { @Override public void onFailure(Request request, Throwable throwable) { } @Override public void onResponse(Response response) throws IOException { } });

Page 30: 2.Connect Sunshine to the Cloud - 시온고 안드로이드 스터디

https://github.com/koush/ionIon

Page 31: 2.Connect Sunshine to the Cloud - 시온고 안드로이드 스터디

Ion 예제Ion.with(context).load("http://api.openweathermap.org/…").asJsonObject().setCallback(new FutureCallback<JsonObject>() { @Override public void onCompleted(Exception e, JsonObject result) { // do stuff with the result or error }});

Page 32: 2.Connect Sunshine to the Cloud - 시온고 안드로이드 스터디

Thank You!Lesson 2 끝!