[Android] AsyncTask 예제
모바일 융합 기술 센터
스마트 앱 창작터 안드로이드 기초 및 실습
Day9Ex1 앞부분 구현 내용 (내용 추가 필요)
package kr.re.mctc.android.day9ex1weatherinfo;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Window;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity {
String mResult = null;
WeatherTask mTask = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setContentView() 앞에서 호출
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.activity_main);
mTask = new WeatherTask();
mTask.execute();
}
class WeatherTask extends AsyncTask<Void, Void, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
setProgressBarIndeterminate(true);
}
@Override
protected String doInBackground(Void... params) {
String query = "http://api.openweathermap.org/data/2.5/weather?q=kumi";
BufferedReader rd = null;
String rLine = "";
StringBuilder result = new StringBuilder();
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(query);
try {
HttpResponse response = httpClient.execute(httpGet);
rd = new BufferedReader(new InputStreamReader(
response.getEntity().getContent()));
while ((rLine = rd.readLine()) != null) {
result.append(rLine);
}
return result.toString();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
setProgressBarIndeterminate(false);
Toast.makeText(MainActivity.this,
result, Toast.LENGTH_SHORT).show();
mResult = result;
}
}
}
'프로그래밍 > Android 프로그래밍' 카테고리의 다른 글
[Android] HttpClient 에러 해결 방법 (0) | 2015.12.01 |
---|---|
[Android] DrawerLayout 나머지 부분 어둡지 않게 만들기 (0) | 2015.08.22 |
[Android] List 예제 (0) | 2014.08.13 |
[Android] BLE (Bluetooth Low Energy) (0) | 2014.06.24 |
[Android] MIDI 프로그래밍 (1) | 2014.06.24 |