Android開発のお勉強

メニュー

E-Mail



非同期でHttpリクエストを送信

 AsyncTaskを利用して非同期処理を実装します。
 ライブドアのWebApiからお天気情報を取得して、表示します。

 AndroidManifest.xmlに下記の追記が必要。
 <uses-permission android:name="android.permission.INTERNET" />

● 非同期処理
 AsyncTaskを利用すれば、画面の描写も実装することができます。
 コンストラクタで描写したいTextViewを渡します。
 doInBackgroundでバックグラウンド処理を実装し、
 onPostExecuteで処理が完了した時の画面描写処理を実装します。


import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.DefaultHttpClient;
import org.xmlpull.v1.XmlPullParser;
import android.os.AsyncTask;
import android.util.Xml;
import android.widget.TextView;

public class MyHttpClient extends AsyncTask<String, String, String> {

    private TextView text;

    public MyHttpClient(TextView text) {
        super();
        this.text = text;
    }


    @Override
    protected String doInBackground(String... arg0) {

        // バックグラウンド処理

        // 東京都の今日のお天気
        String uri = "http://weather.livedoor.com/forecast/webservice/rest/v1?city=63&day=today";

        // Httpリクエストを送信
        DefaultHttpClient client = new DefaultHttpClient();
        HttpUriRequest req = new HttpGet(uri);
        HttpResponse res = null;
        String telop = "";

        try {
            res = client.execute(req);

            // 取得したXMLから天気情報を取り出す
            XmlPullParser xmlPullParser = Xml.newPullParser();
            xmlPullParser.setInput(res.getEntity().getContent(),"UTF-8");

            for(int e = xmlPullParser.getEventType(); e != XmlPullParser.END_DOCUMENT; e = xmlPullParser.next()){
                if(e == XmlPullParser.START_TAG && xmlPullParser.getName().equals("telop")){
                    telop = xmlPullParser.nextText();
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return telop;

    }

    protected void onPostExecute(String res) {
        //バックグラウンド処理が完了した時の処理
        this.text.setText(res);
    }

}




● Activity
 作成したAsyncTaskのクラスを生成して、バックグランド処理を実行します。
 


import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.TextView;

public class HttpClientActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_http_client);

        // バックグラウンド処理を実行
        MyHttpClient client = new MyHttpClient((TextView)findViewById(R.id.textView1));
        client.execute("");

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_http_client, menu);
        return true;
    }
}






Copyright (C) Androidアプリ開発のお勉強. All Rights Reserved.