- Android 基礎
- Android - 首頁
- Android - 概述
- Android - 環境搭建
- Android - 架構
- Android - 應用元件
- Android - Hello World 例子
- Android - 資源
- Android - 活動 (Activities)
- Android - 服務 (Services)
- Android - 廣播接收器 (Broadcast Receivers)
- Android - 內容提供器 (Content Providers)
- Android - 碎片 (Fragments)
- Android - 意圖/過濾器 (Intents/Filters)
- Android - 使用者介面
- Android - UI 佈局
- Android - UI 控制元件
- Android - 事件處理
- Android - 樣式和主題
- Android - 自定義元件
- Android 高階概念
- Android - 拖放
- Android - 通知
- 基於位置的服務
- Android - 傳送郵件
- Android - 傳送簡訊
- Android - 電話呼叫
- 釋出 Android 應用
- Android 實用示例
- Android - 警報對話方塊
- Android - 動畫
- Android - 音訊捕獲
- Android - AudioManager
- Android - 自動完成
- Android - 最佳實踐
- Android - 藍牙
- Android - 相機
- Android - 剪貼簿
- Android - 自定義字型
- Android - 資料備份
- Android - 開發者工具
- Android - 模擬器
- Android - Facebook 整合
- Android - 手勢
- Android - Google 地圖
- Android - 圖片效果
- Android - ImageSwitcher
- Android - 內部儲存
- Android - JetPlayer
- Android - JSON 解析器
- Android - LinkedIn 整合
- Android - 載入動畫 (Loading Spinner)
- Android - 本地化
- Android - 登入介面
- Android - MediaPlayer
- Android - 多點觸控
- Android - 導航
- Android - 網路連線
- Android - NFC 指南
- Android - PHP/MySQL
- Android - 進度環 (Progress Circle)
- Android - 進度條 (ProgressBar)
- Android - 推送通知
- Android - RenderScript
- Android - RSS 閱讀器
- Android - 螢幕錄製
- Android - SDK 管理器
- Android - 感測器
- Android - 會話管理
- Android - 共享首選項
- Android - SIP 協議
- Android - 拼寫檢查器
- Android - SQLite 資料庫
- Android - 支援庫
- Android - 測試
- Android - 文字轉語音
- Android - TextureView
- Android - Twitter 整合
- Android - UI 設計
- Android - UI 模式
- Android - UI 測試
- Android - WebView 佈局
- Android - Wi-Fi
- Android - 小工具 (Widgets)
- Android - XML 解析器
- Android 實用資源
- Android - 問答
- Android - 實用資源
- 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();
}
}
除了已連線狀態外,網路還可以達到其他狀態。它們列在下面:
| 序號 | 狀態 |
|---|---|
| 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 檔案,然後單擊工具欄中的執行
圖示。在啟動應用程式之前,Android Studio 將顯示以下視窗,讓您選擇要在其中執行 Android 應用程式的選項。
選擇您的移動裝置作為選項,然後檢查您的移動裝置,它將顯示以下螢幕:
現在只需點選按鈕,它將檢查網際網路連線,並將下載圖片。
輸出如下所示,它已從網際網路上獲取徽標。
