• Android Video Tutorials

Android - 網路連線



Android 允許您的應用程式連線到網際網路或任何其他本地網路,並允許您執行網路操作。

裝置可以具有各種型別的網路連線。本章重點介紹使用 Wi-Fi 或行動網路連線。

檢查網路連線

在執行任何網路操作之前,您必須首先檢查是否已連線到該網路或網際網路等。為此,Android 提供了 **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();
   }
}

除了已連線狀態外,網路還可以達到其他狀態。它們列在下面:

序號 狀態
1 正在連線
2 已斷開連線
3 正在斷開連線
4 已暫停
5 未知

執行網路操作

檢查您已連線到網際網路後,您可以執行任何網路操作。這裡我們正在從 URL 獲取網站的 HTML。

Android 提供了 **HttpURLConnection** 和 **URL** 類來處理這些操作。您需要透過提供網站連結來例項化 URL 類的物件。其語法如下:

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

之後,您需要呼叫 url 類的 **openConnection** 方法,並將其接收在 HttpURLConnection 物件中。之後,您需要呼叫 HttpURLConnection 類的 **connect** 方法。

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

您需要做的最後一件事是從網站獲取 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";
}

除了 connect 方法外,HttpURLConnection 類中還提供了其他方法。它們列在下面:

序號 方法和描述
1

disconnect()

此方法釋放此連線,以便其資源可以被重用或關閉。

2

getRequestMethod()

此方法返回將用於向遠端 HTTP 伺服器發出請求的請求方法。

3

getResponseCode()

此方法返回遠端 HTTP 伺服器返回的響應程式碼。

4

setRequestMethod(String method)

此方法設定將傳送到遠端 HTTP 伺服器的請求命令。

5

usingProxy()

此方法返回此連線是否使用代理伺服器。

示例

以下示例演示了 HttpURLConnection 類的用法。它建立一個基本的應用程式,允許您從給定的網頁下載 HTML。

要試驗此示例,您需要在連線了 wifi 網際網路的實際裝置上執行它。

步驟 描述
1 您將使用 Android Studio IDE 在 com.tutorialspoint.myapplication 包下建立一個 Android 應用程式。
2 修改 src/MainActivity.java 檔案以新增 Activity 程式碼。
4 修改佈局 XML 檔案 res/layout/activity_main.xml,如果需要,新增任何 GUI 元件。
6 修改 AndroidManifest.xml 以新增必要的許可權。
7 執行應用程式,選擇正在執行的 Android 裝置,將應用程式安裝在其上並驗證結果。

以下是 **src/MainActivity.java** 的內容。

package com.tutorialspoint.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("https://tutorialspoint.tw/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.tutorialspoint.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 執行應用程式,請開啟專案的一個 Activity 檔案,然後單擊工具欄中的執行 Eclipse Run Icon 圖示。在啟動應用程式之前,Android Studio 將顯示以下視窗,讓您選擇要在其中執行 Android 應用程式的選項。

Anroid Network Connection Tutorial

選擇您的移動裝置作為選項,然後檢查您的移動裝置,它將顯示以下螢幕:

Anroid Network Connection Tutorial

現在只需點選按鈕,它將檢查網際網路連線,並將下載圖片。

Anroid Network Connection Tutorial

輸出如下所示,它已從網際網路上獲取徽標。

Anroid Network Connection Tutorial
廣告
© . All rights reserved.