Android - 概述

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


除了这个连接状态,网络还可以实现其他状态.它们列在下面和下面;

Sr.NoState
1正在连接
2断开连接
3断开连接
4暂停
5未知

执行网络操作

检查您是否已连接到互联网后,您可以执行任何网络操作.这里我们从网址获取网站的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";
}


除了这个连接方法,HttpURLConnection类还有其他方法.它们列在下面和下面;

Sr.No方法&描述
1

断开连接()

此方法释放此连接,以便其资源可以重复使用或关闭

2

getRequestMethod()

此方法返回将用于向远程HTTP服务器发出请求的请求方法

3

getResponseCode()

此方法返回遥控器返回的响应代码HTTP服务器

4

setRequestMethod(String method)

此方法设置将发送到远程HTTP服务器的请求命令

5

usingProxy()

此方法返回此连接是否使用代理服务器

示例

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

要试验这个例子,您需要在连接了无线互联网的实际设备上运行它.

步骤描述
1您将使用Android studio IDE在com.it1352.myapplication包下创建一个Android应用程序.
2修改src/MainActivity.java文件以添加活动代码.
4修改布局XML文件res/layout/activity_main.xml如果需要,添加任何GUI组件.
6修改AndroidManifest.xml以添加必要的权限.
7运行应用程序并选择正在运行的Android设备并在其上安装应用程序并验证结果.

以下是 src/MainActivity.java 的内容.

package com.IT屋.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.IT屋.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.IT屋.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运行应用程序,打开项目的一个活动文件,然后单击运行Eclipse Run Icon icon从工具栏.在开始申请之前,Android studio将显示以下窗口,以选择您要运行Android应用程序的选项.

Anroid网络连接教程

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

Anroid网络连接教程

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

Anroid网络连接教程

输出如下,它已获取徽标来自互联网.

Anroid网络连接教程