Connecting to the Network
翻訳してからhttp://developer.android.com/training/basics/network-ops/connecting.html この授業では、簡単なアプリケーションをインターネットに接続する方法を教えます.いくつかの例を説明します.これらの設計に従って、甚だしきに至っては、あなたの一番簡単なネットワーク接続アプリケーションでもあります.
本明細書で言及したネットワーク動作を実行するために、あなたの構成には以下のような権限が必要です.
ほとんどのネットワーク接続が必要なAndroidアプリケーションは、HTTPを用いてデータを送信し受信する.Androidプラットフォームは、
Check the Network COnnection
あなたのアプリケーションがネットワークに接続する前に、ネットワーク接続があるかどうかを確認する必要があります.
ネットワーク操作には予測不可能な遅延が含まれます.悪いユーザ体験を回避するために、常に単一の非UIスレッド内でネットワーク動作を実行する. ユーザがボタンを押すと、 に伝達される. を使用する. を作成する.このURLオブジェクトは、 を確立するために使用される.接続が確立されると、 をストリーミングする.ストリームコンテンツは、 に変換することができる.最後に、 を示す.
Connect and Download Data
あなたのプロセスがネットワークトランザクションを実行する場合、
以下のコード段において、
Covert the InputStream to a String
本明細書で言及したネットワーク動作を実行するために、あなたの構成には以下のような権限が必要です.
<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)
、DownloadWebpageTask
はAsyncTask
のサブクラスを含み、DownloadWebpageTask
はAsyncTask
以下の方法を実現する.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オブジェクトHttpURLConnection
HttpURLConnection
オブジェクトは、ウェブページのコンテンツreadIt()
方法により、ストリームオブジェクトを文字列オブジェクトAsyncTask
のonPostExecute()
方法は、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 String
getResponseCode()
はビットの読み取り可能なデータであり、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);
}