Android-network-connection

提供:Dev Guides
移動先:案内検索

Android-ネットワーク接続

Androidでは、アプリケーションをインターネットまたはその他のローカルネットワークに接続し、ネットワーク操作を実行できます。

デバイスには、さまざまなタイプのネットワーク接続を設定できます。 この章では、Wi-Fiまたはモバイルネットワーク接続の使用に焦点を当てます。

ネットワーク接続の確認

ネットワーク操作を実行する前に、まずそのネットワークまたはインターネットe.t.cに接続されていることを確認する必要があります。 このアンドロイドは ConnectivityManager クラスを提供します。 * getSystemService()*メソッドを呼び出して、このクラスのオブジェクトをインスタンス化する必要があります。 その構文は以下のとおりです-

ConnectivityManager check = (ConnectivityManager)
this.context.getSystemService(Context.CONNECTIVITY_SERVICE);

ConnectivityManagerクラスのオブジェクトをインスタンス化すると、 getAllNetworkInfo メソッドを使用してすべてのネットワークの情報を取得できます。 このメソッドは、 NetworkInfo の配列を返します。 そのため、このように受け取る必要があります。

NetworkInfo[] info = check.getAllNetworkInfo();

最後に行う必要があるのは、ネットワークの*接続状態*を確認することです。 その構文は以下のとおりです-

for (int i = 0; i<info.length; i++){
   if (info[i].getState() == NetworkInfo.State.CONNECTED){
      Toast.makeText(context, "Internet is connected
      Toast.LENGTH_SHORT).show();
   }
}

この接続状態とは別に、ネットワークが達成できる他の状態があります。 それらは以下にリストされています-

Sr.No State
1 Connecting
2 Disconnected
3 Disconnecting
4 Suspended
5 Unknown

ネットワーク操作の実行

インターネットに接続していることを確認したら、任意のネットワーク操作を実行できます。 ここでは、WebサイトのhtmlをURLから取得しています。

Androidは、これらの操作を処理する HttpURLConnection および URL クラスを提供します。 Webサイトのリンクを提供して、URLクラスのオブジェクトをインスタンス化する必要があります。 その構文は次のとおりです-

String link = "http://www.google.com";
URL url = new URL(link);

その後、urlクラスの openConnection メソッドを呼び出して、HttpURLConnectionオブジェクトで受信する必要があります。 その後、HttpURLConnectionクラスの connect メソッドを呼び出す必要があります。

HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.connect();

そして最後に行う必要があるのは、WebサイトからHTMLを取得することです。 これには、 InputStream および BufferedReader クラスを使用します。 その構文は以下のとおりです-

InputStream is = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
String webPage = "",data="";

while ((data = reader.readLine()) != null){
   webPage += data + "\n";
}

この接続メソッドとは別に、HttpURLConnectionクラスで使用できる他のメソッドがあります。 それらは以下にリストされています-

Sr.No Method & description
1

disconnect()

このメソッドはこの接続を解放して、リソースを再利用または閉じることができるようにします

2

getRequestMethod()

このメソッドは、リモートHTTPサーバーへの要求を行うために使用される要求メソッドを返します

3

getResponseCode()

このメソッドは、リモートHTTPサーバーによって返された応答コードを返します

4

setRequestMethod(String method)

このメソッドは、リモートHTTPサーバーに送信される要求コマンドを設定します

5

usingProxy()

このメソッドは、この接続がプロキシサーバーを使用するかどうかを返します

以下の例は、HttpURLConnectionクラスの使用を示しています。 特定のWebページからHTMLをダウンロードできる基本的なアプリケーションを作成します。

この例を試すには、wifiインターネットが接続されている実際のデバイスでこれを実行する必要があります。

Steps Description
1 You will use Android studio IDE to create an Android application under a package com.finddevguides.myapplication.
2 Modify src/MainActivity.java file to add Activity code.
4 Modify layout XML file res/layout/activity_main.xml add any GUI component if required.
6 Modify AndroidManifest.xml to add necessary permissions.
7 Run the application and choose a running android device and install the application on it and verify the results.
*src/MainActivity.java* のコンテンツは次のとおりです。
package com.finddevguides.myapplication;

import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

import android.net.ConnectivityManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.ActionBarActivity;
import android.view.View;

import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import java.io.IOException;
import java.io.InputStream;

import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

public class MainActivity extends ActionBarActivity {
   private ProgressDialog progressDialog;
   private Bitmap bitmap = null;
   Button b1;

   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      b1 = (Button) findViewById(R.id.button);

      b1.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            checkInternetConenction();
            downloadImage("http://www.finddevguides.com/green/images/logo.png");
         }
      });
   }

   private void downloadImage(String urlStr) {
      progressDialog = ProgressDialog.show(this, "", "Downloading Image from " + urlStr);
      final String url = urlStr;

      new Thread() {
         public void run() {
            InputStream in = null;

            Message msg = Message.obtain();
            msg.what = 1;

            try {
               in = openHttpConnection(url);
               bitmap = BitmapFactory.decodeStream(in);
               Bundle b = new Bundle();
               b.putParcelable("bitmap", bitmap);
               msg.setData(b);
               in.close();
            }catch (IOException e1) {
               e1.printStackTrace();
            }
            messageHandler.sendMessage(msg);
         }
      }.start();
   }

   private InputStream openHttpConnection(String urlStr) {
      InputStream in = null;
      int resCode = -1;

      try {
         URL url = new URL(urlStr);
         URLConnection urlConn = url.openConnection();

         if (!(urlConn instanceof HttpURLConnection)) {
            throw new IOException("URL is not an Http URL");
         }

         HttpURLConnection httpConn = (HttpURLConnection) urlConn;
         httpConn.setAllowUserInteraction(false);
         httpConn.setInstanceFollowRedirects(true);
         httpConn.setRequestMethod("GET");
         httpConn.connect();
         resCode = httpConn.getResponseCode();

         if (resCode == HttpURLConnection.HTTP_OK) {
            in = httpConn.getInputStream();
         }
      }catch (MalformedURLException e) {
         e.printStackTrace();
      }catch (IOException e) {
         e.printStackTrace();
      }
      return in;
   }

   private Handler messageHandler = new Handler() {
      public void handleMessage(Message msg) {
         super.handleMessage(msg);
         ImageView img = (ImageView) findViewById(R.id.imageView);
         img.setImageBitmap((Bitmap) (msg.getData().getParcelable("bitmap")));
         progressDialog.dismiss();
      }
   };

   private boolean checkInternetConenction() {
     //get Connectivity Manager object to check connection
      ConnectivityManager connec
         =(ConnectivityManager)getSystemService(getBaseContext().CONNECTIVITY_SERVICE);

     //Check for network connections
      if ( connec.getNetworkInfo(0).getState() ==
         android.net.NetworkInfo.State.CONNECTED ||
         connec.getNetworkInfo(0).getState() ==
         android.net.NetworkInfo.State.CONNECTING ||
         connec.getNetworkInfo(1).getState() ==
         android.net.NetworkInfo.State.CONNECTING ||
         connec.getNetworkInfo(1).getState() == android.net.NetworkInfo.State.CONNECTED ) {
            Toast.makeText(this, " Connected ", Toast.LENGTH_LONG).show();
            return true;
         }else if (
            connec.getNetworkInfo(0).getState() ==
            android.net.NetworkInfo.State.DISCONNECTED ||
            connec.getNetworkInfo(1).getState() ==
            android.net.NetworkInfo.State.DISCONNECTED  ) {
               Toast.makeText(this, " Not Connected ", Toast.LENGTH_LONG).show();
               return false;
            }
         return false;
   }

}
*activity_main.xml* の内容は次のとおりです。
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
   android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
   android:paddingRight="@dimen/activity_horizontal_margin"
   android:paddingTop="@dimen/activity_vertical_margin"
   android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">

   <TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="UI Animator Viewer"
      android:id="@+id/textView"
      android:textSize="25sp"
      android:layout_centerHorizontal="true"/>

   <TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Tutorials point"
      android:id="@+id/textView2"
      android:layout_below="@+id/textView"
      android:layout_alignRight="@+id/textView"
      android:layout_alignEnd="@+id/textView"
      android:textColor="#ff36ff15"
      android:textIsSelectable="false"
      android:textSize="35dp"/>

   <ImageView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:id="@+id/imageView"
      android:layout_below="@+id/textView2"
      android:layout_centerHorizontal="true"/>

   <Button
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Button"
      android:id="@+id/button"
      android:layout_below="@+id/imageView"
      android:layout_centerHorizontal="true"
      android:layout_marginTop="76dp"/>

</RelativeLayout>
*Strings.xml* の内容は次のとおりです。
<resources>
   <string name="app_name">My Application</string>
</resources>
*AndroidManifest.xml* のコンテンツは次のとおりです。
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="com.finddevguides.myapplication" >
   <uses-permission android:name="android.permission.INTERNET"></uses-permission>
   <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>

   <application
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      android:theme="@style/AppTheme" >

      <activity
         android:name=".MainActivity"
         android:label="@string/app_name" >

         <intent-filter>
            <action android:name="android.intent.action.MAIN"/>
            <category android:name="android.intent.category.LAUNCHER"/>
         </intent-filter>

      </activity>

   </application>
</manifest>

アプリケーションを実行してみましょう。 実際のAndroidモバイルデバイスをコンピューターに接続していると思います。 Android Studioからアプリを実行するには、プロジェクトのアクティビティファイルの1つを開き、ツールバーの[画像の実行:/android/images/eclipse_run.jpg [Eclipse Run Icon]アイコンをクリックします。 アプリケーションを開始する前に、Androidスタジオは次のウィンドウを表示して、Androidアプリケーションを実行するオプションを選択します。

Androidネットワーク接続チュートリアル

オプションとしてモバイルデバイスを選択し、次の画面を表示するモバイルデバイスを確認します-

Androidネットワーク接続チュートリアル

ボタンをクリックするだけで、インターネット接続を確認し、画像をダウンロードします。

Androidネットワーク接続チュートリアル

アウトは次のようになり、インターネットからロゴを取得しました。

Androidネットワーク接続チュートリアル