Android 简明教程

Android - Network Connection

Android 让您的应用程序连接到互联网或任何其他本地网络,并允许您执行网络操作。

Android lets your application connect to the internet or any other local network and allows you to perform network operations.

一个设备可以有各种类型的网络连接。本章重点介绍如何使用 Wi-Fi 或移动网络连接。

A device can have various types of network connections. This chapter focuses on using either a Wi-Fi or a mobile network connection.

Checking Network Connection

在执行任何网络操作之前,您必须先检查是否已连接到该网络或互联网等。为此,Android 提供了 ConnectivityManager 类。您需要通过调用 getSystemService() 方法来实例化此类的对象。其语法如下所示:−

Before you perform any network operations, you must first check that are you connected to that network or internet e.t.c. For this android provides ConnectivityManager class. You need to instantiate an object of this class by calling getSystemService() method. Its syntax is given below −

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

一旦实例化 ConnectivityManager 类的对象,就可以使用 getAllNetworkInfo 方法获取所有网络的信息。此方法返回 NetworkInfo 数组。所以你必须像这样接收它。

Once you instantiate the object of ConnectivityManager class, you can use getAllNetworkInfo method to get the information of all the networks. This method returns an array of NetworkInfo. So you have to receive it like this.

NetworkInfo[] info = check.getAllNetworkInfo();

您需要做的最后一件事是检查网络的 Connected State 。其语法如下所示:−

The last thing you need to do is to check Connected State of the network. Its syntax is given below −

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();
   }
}

除了这些已连接状态外,网络还可以达到其他状态。它们列在下面:−

Apart from this connected states, there are other states a network can achieve. They are listed below −

Sr.No

State

1

Connecting

2

Disconnected

3

Disconnecting

4

Suspended

5

Unknown

Performing Network Operations

在检查您已连接到互联网之后,您可以执行任何网络操作。此处我们正在从一个网址获取网站的 HTML。

After checking that you are connected to the internet, you can perform any network operation. Here we are fetching the html of a website from a url.

Android 提供了 HttpURLConnectionURL 类来处理这些操作。您需要通过提供网站链接来实例化 URL 类的对象。其语法如下:−

Android provides HttpURLConnection and URL class to handle these operations. You need to instantiate an object of URL class by providing the link of website. Its syntax is as follows −

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

之后,您需要调用 URL 类的 openConnection 方法并将其接收在 HttpURLConnection 对象中。之后,您需要调用 HttpURLConnection 类的 connect 方法。

After that you need to call openConnection method of url class and receive it in a HttpURLConnection object. After that you need to call the connect method of HttpURLConnection class.

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

您最后需要做的就是从网站获取 HTML。为此,您将使用 InputStreamBufferedReader 类。其语法如下所示:−

And the last thing you need to do is to fetch the HTML from the website. For this you will use InputStream and BufferedReader class. Its syntax is given below −

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 类中还提供了其他方法。它们列在下面:−

Apart from this connect method, there are other methods available in HttpURLConnection class. They are listed below −

Sr.No

Method & description

1

disconnect() This method releases this connection so that its resources may be either reused or closed

2

getRequestMethod() This method returns the request method which will be used to make the request to the remote HTTP server

3

getResponseCode() This method returns response code returned by the remote HTTP server

4

setRequestMethod(String method) This method Sets the request command which will be sent to the remote HTTP server

5

usingProxy() This method returns whether this connection uses a proxy server or not

Example

以下示例演示如何使用 HttpURLConnection 类。它创建了一个基本应用程序,允许您从给定的网页下载 HTML。

The below example demonstrates the use of HttpURLConnection class. It creates a basic application that allows you to download HTML from a given web page.

要尝试此示例,您需要在连接 WiFi 网络的实际设备上运行此应用程序。

To experiment with this example, you need to run this on an actual device on which wifi internet is connected .

Steps

Description

1

You will use Android studio IDE to create an Android application under a package com.tutorialspoint.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 的内容。

Here is the content of 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://www.tutorialspoint.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 的内容。

Here is the content of 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 的内容。

Here is the content of Strings.xml.

<resources>
   <string name="app_name">My Application</string>
</resources>

以下是 AndroidManifest.xml 的内容

Here is the content of 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 工作室运行应用程序,请打开一个项目的活动文件,并单击工具栏中的运行图标。在启动应用程序之前,Android 工作室将显示以下窗口选择您希望运行 Android 应用程序的选项。

Let’s try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project’s activity files and click Run icon from the tool bar. Before starting your application, Android studio will display following window to select an option where you want to run your Android application.

choose device

选择你的移动设备作为选项,然后检查你的移动设备,它将显示以下屏幕 −

Select your mobile device as an option and then check your mobile device which will display following screen −

network

现在,只需单击按钮,它将检查互联网连接并下载图像。

Now just click on button, It will check internet connection as well as it will download image.

network1

输出如下,它已从互联网获取徽标。

Out would be as follows and it has fetch the logo from internet.

network2