Connecting to the Network


翻訳してからhttp://developer.android.com/training/basics/network-ops/connecting.html この授業では、簡単なアプリケーションをインターネットに接続する方法を教えます.いくつかの例を説明します.これらの設計に従って、甚だしきに至っては、あなたの一番簡単なネットワーク接続アプリケーションでもあります.
本明細書で言及したネットワーク動作を実行するために、あなたの構成には以下のような権限が必要です.
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Choose an HTTP Cient
ほとんどのネットワーク接続が必要なAndroidアプリケーションは、HTTPを用いてデータを送信し受信する.Androidプラットフォームは、HttpURLConnectionクライアントを含み、HTTPS、ストリーミングアップとダウンロード、タイムアウト、IPv 6、接続プールをサポートしています.
Check the Network COnnection
あなたのアプリケーションがネットワークに接続する前に、ネットワーク接続があるかどうかを確認する必要があります.getActiveNetworkInfo()isConnected()を使用してもいいです.デバイスはネットワークの範囲を超えているかもしれません.または、ユーザはWi-Fiとモバイルデータを禁止しています.
public void myClickHandler(View view) {
    ...
    ConnectivityManager connMgr = (ConnectivityManager) 
        getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
    if (networkInfo != null && networkInfo.isConnected()) {
        // fetch data
    } else {
        // display error
    }
    ...
}
Perform Network Operations on a Separate Thread
ネットワーク操作には予測不可能な遅延が含まれます.悪いユーザ体験を回避するために、常に単一の非UIスレッド内でネットワーク動作を実行する.AsyncTaskは、最新の方法を提供して、主UIスレッドから新しいタスクを開始する.以下のフラグメントにおいて、myClickHandler()方法はnew DownloadWebpageTask().execute(stringUrl)DownloadWebpageTaskAsyncTaskのサブクラスを含み、DownloadWebpageTaskAsyncTask以下の方法を実現する.
  • doInBackground()は、パラメータとしてページアドレスを伝えるdownloadUrl()方法を実行している.downloadUrl()方法は、ウェブページのコンテンツを取得して処理し、それが完了すると、結果を返します.
  • onPostExecute()は、返信された文字列を取り出し、UI上に表示する.
  • public class HttpExampleActivity extends Activity {
        private static final String DEBUG_TAG = "HttpExample";
        private EditText urlText;
        private TextView textView;
    
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);   
            urlText = (EditText) findViewById(R.id.myUrl);
            textView = (TextView) findViewById(R.id.myText);
        }
    
        // When user clicks button, calls AsyncTask.
        // Before attempting to fetch the URL, makes sure that there is a network connection.
        public void myClickHandler(View view) {
            // Gets the URL from the UI's text field.
            String stringUrl = urlText.getText().toString();
            ConnectivityManager connMgr = (ConnectivityManager) 
                getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
            if (networkInfo != null && networkInfo.isConnected()) {
                new DownloadWebpageTask().execute(stringUrl);
            } else {
                textView.setText("No network connection available.");
            }
        }
    
         // Uses AsyncTask to create a task away from the main UI thread. This task takes a 
         // URL string and uses it to create an HttpUrlConnection. Once the connection
         // has been established, the AsyncTask downloads the contents of the webpage as
         // an InputStream. Finally, the InputStream is converted into a string, which is
         // displayed in the UI by the AsyncTask's onPostExecute method.
         private class DownloadWebpageTask extends AsyncTask<String, Void, String> {
            @Override
            protected String doInBackground(String... urls) {
    
                // params comes from the execute() call: params[0] is the url.
                try {
                    return downloadUrl(urls[0]);
                } catch (IOException e) {
                    return "Unable to retrieve web page. URL may be invalid.";
                }
            }
            // onPostExecute displays the results of the AsyncTask.
            @Override
            protected void onPostExecute(String result) {
                textView.setText(result);
           }
        }
        ...
    }
    コードセグメントに対応するイベントの流れは以下の通りです.
  • ユーザがボタンを押すと、myClickHandler()がトリガされ、特定のURLがAsyncTaskのサブクラスDownloadWebpageTask
  • に伝達される.
  • AsyncTaskの方法doInBackground()は、downloadUrl()の方法
  • を使用する.
  • downloadUrl()方法は、URL文字列を取得して、URLオブジェクト
  • を作成する.
  • このURLオブジェクトは、HttpURLConnection
  • を確立するために使用される.
  • 接続が確立されると、HttpURLConnectionオブジェクトは、ウェブページのコンテンツ
  • をストリーミングする.
  • ストリームコンテンツは、readIt()方法により、ストリームオブジェクトを文字列オブジェクト
  • に変換することができる.
  • 最後に、AsyncTaskonPostExecute()方法は、UIプロセスに文字列
  • を示す.
    Connect and Download Data
    あなたのプロセスがネットワークトランザクションを実行する場合、HttpURLConnectionを使用してGETとデータのダウンロードを実行できます.connect()を使用した後、getInputStream()を介してデータのストリームオブジェクトを得ることができます.
    以下のコード段において、doInBackground()方法は、downloadUrl()方法を用いて、特定のURLを取得し、downloadUrl()を介してネットワークに接続し、一旦接続が確立されると、アプリケーションはHttpURLConnectionを用いてストリームオブジェクトを取得する.
    // Given a URL, establishes an HttpUrlConnection and retrieves
    // the web page content as a InputStream, which it returns as
    // a string.
    private String downloadUrl(String myurl) throws IOException {
        InputStream is = null;
        // Only display the first 500 characters of the retrieved
        // web page content.
        int len = 500;
    
        try {
            URL url = new URL(myurl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(10000 /* milliseconds */);
            conn.setConnectTimeout(15000 /* milliseconds */);
            conn.setRequestMethod("GET");
            conn.setDoInput(true);
            // Starts the query
            conn.connect();
            int response = conn.getResponseCode();
            Log.d(DEBUG_TAG, "The response is: " + response);
            is = conn.getInputStream();
    
            // Convert the InputStream into a string
            String contentAsString = readIt(is, len);
            return contentAsString;
    
        // Makes sure that the InputStream is closed after the app is
        // finished using it.
        } finally {
            if (is != null) {
                is.close();
            } 
        }
    }
    
    getInputStream()方法は、接続に関する追加情報を取得するために有効な方法である状態コードを返す.200ステータスコードは成功を表します.
    Covert the InputStream to a StringgetResponseCode()はビットの読み取り可能なデータであり、InputStreamを取得した後、それを復号して目標データタイプに変換するのは正常である.例えば、画像データをダウンロードしているなら、復号して次のように展示することができます.
    InputStream is = null;
    ...
    Bitmap bitmap = BitmapFactory.decodeStream(is);
    ImageView imageView = (ImageView) findViewById(R.id.image_view);
    imageView.setImageBitmap(bitmap);
    上記の例に示すように、InputStreamは、ウェブページのテキストコンテンツを表し、次に、InputStreamを文字列に変換する方法を示し、メインUIに表示する.
    // Reads an InputStream and converts it to a String.
    public String readIt(InputStream stream, int len) throws IOException, UnsupportedEncodingException {
        Reader reader = null;
        reader = new InputStreamReader(stream, "UTF-8");        
        char[] buffer = new char[len];
        reader.read(buffer);
        return new String(buffer);
    }