`
hududumo
  • 浏览: 238698 次
文章分类
社区版块
存档分类
最新评论

使用Android中的网络连接

 
阅读更多

本文简介

本文综述了Android应用程序开发可用的联网选项以及有关Android基本联网技巧等内容。

本文提供学习如何针对应用程序开发利用Android的联网选项。当与环境监测系统一起使用时,探索一个要求联网的真实世界的应用程序。本文中提供了可供实践用的示例代码片段。

范围:

本文旨在为希望简单了解Android编程的初学者而设计。本文逐步指导初学者来开发Android中基于网络的应用程序。本文假定用户已经安装了可开发应用程序的Android和必要的工具,同样假定用户已熟悉Java或熟悉基于对象的编程概念。

简介

网络编程在无线应用程序开发过程中起到了重要的作用。Android包括Apache HttpClient库,此库为执行Android中的网络操作之首选方法。Android还可允许通过标准的Java联网API(java.net包)来访问网络。即便使用Java.net包,也是在内部使用该Apache库。

为了访问互联网,你的应用程序需要获取“android.permission.INTERNET”许可

Android中与网络相关的包

以下内容为Android SDK中与网络相关的部分包

•java.net

提供联网相关的类,包括流和数据报套接字、互联网协议以及通用的HTTP处理。此为多用途的联网资源。经验丰富的Java开发人员可立即使用此惯用的包来创建应用程序。

•java.io

尽管未明确联网,但其仍然非常重要。此包中的各种类通过其他Java包中提供的套接字和链接来使用。它们也可用来与本地文件进行交互(与网络进行交互时经常发生)。

•java.nio

包含表示具体数据类型的缓冲的各种类。便于基于Java语言的两个端点之间的网络通信。

•org.apache.*

表示可为进行HTTP通信提供精细控制和功能的各种包。你可将Apache识别为普通的开源Web服务器。

•android.net

包括核心java.net.*类之外的各种附加的网络接入套接字。此包包括URL类,其通常在传统联网之外的Android应用程序开发中使用。

•android.net.http

包含可操作SSL证书的各种类。

•android.net.wifi

包含可管理Android平台中WiFi(802.11无线以太网)所有方面的各种类。并非所有的设备均配备有WiFi能力,尤其随着Android在对制造商(如诺基亚和LG)手机的翻盖手机研发方面取得了进展。

•android.telephony.gsm

包含管理和发送短信(文本)消息所要求的各种类。随着时间的推移,可能将引入一种附加的包,以提供有关非GSM网络(如CDMA或类似android.telephony.cdma)的类似功能。

Android联网

使用Apache HttpClient库

在Apache HttpClient库中,以下内容为对网络连接有用的各种包。

  • org.apache.http.HttpResponse

  • org.apache.http.client.HttpClient

  • org.apache.http.client.methods.HttpGet

  • org.apache.http.impl.client.DefaultHttpClient

HttpClient httpclient=new DefaultHttpClient();

如欲从服务器检索此信息,使用HttpGet类构造器

HttpGet request=new HttpGet(“http://innovator.samsungmobile.com”);

然后通过HttpClient类的execute()方法中的HttpGet对象来检索HttpResponse对象

HttpResponse response = client.execute(request);

接着读取已检索的响应

BufferedReader rd = new BufferedReader

(new InputStreamReader(response.getEntity().getContent()));

String line = "";

while ((line = rd.readLine()) != null) {

Log.d(“output: ”,line);

}

示例

以下提供内容为可使用Apache HttpClient库来进行网络连接的示例代码片段。添加许可“android.permission.INTERNET”至"AndroidManifest.xml"中,从而可允许你的应用程序访问网络。

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>

<manifest xmlns:android="http://schemas.android.com/apk/res/android"

package="com.apache"

android:versionCode="1"

android:versionName="1.0">

<uses-sdk android:minSdkVersion="8" />

<uses-permission android:name="android.permission.INTERNET"></uses-permission>

<application android:icon="@drawable/icon" android:label="@string/app_name">

<activity android:name=".ApacheConnection"

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>

使用activity“ApacheConnection”来创建项目“com.apache”。将布局“main.xml”更改为如下。

Main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

android:orientation="vertical"

android:layout_width="fill_parent"

android:layout_height="fill_parent"

>

<TextView

android:text="Enter URL"

android:id="@+id/textView1"

android:layout_width="wrap_content"

android:layout_height="wrap_content">

</TextView>

<EditText

android:id="@+id/editText1"

android:layout_width="match_parent"

android:text="http://innovator.samsungmobile.com"

android:layout_height="wrap_content">

</EditText>

<Button

android:text="Click Here"

android:id="@+id/button1"

android:layout_width="wrap_content"

android:layout_height="wrap_content">

</Button>

<EditText

android:id="@+id/editText2"

android:layout_width="match_parent"

android:layout_height="fill_parent">

</EditText>

</LinearLayout>

此刻在java中创建一个代码,此代码将可允许查看HTML代码。

ApacheConnection.java

package com.apache;

import java.io.BufferedReader;

import java.io.InputStreamReader;

import org.apache.http.HttpResponse;

import org.apache.http.client.HttpClient;

import org.apache.http.client.methods.HttpGet;

import org.apache.http.impl.client.DefaultHttpClient;

import android.app.Activity;

import android.os.Bundle;

import android.view.View;

import android.view.View.OnClickListener;

import android.widget.Button;

import android.widget.TextView;

public class ApacheConnection extends Activity {

Button bt;

TextView textView1;

TextView textView2;

/** Called when the activity is first created. */

@Override

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.main);

bt = (Button) findViewById(R.id.button1);

textView1 = (TextView) findViewById(R.id.editText1);

textView2 = (TextView) findViewById(R.id.editText2);

bt.setOnClickListener(new OnClickListener() {

@Override

public void onClick(View v) {

// TODO Auto-generated method stub

textView2.setText("");

try {

/*Apache HttpClient Library*/

HttpClient client = new DefaultHttpClient();

HttpGet request = new HttpGet(textView1.getText().toString());

HttpResponse response = client.execute(request);

/* response code*/

BufferedReader rd = new BufferedReader(

new InputStreamReader(response.getEntity().getContent()));

String line = "";

while ((line = rd.readLine()) != null) {

textView2.append(line);

}

} catch (Exception exe) {

exe.printStackTrace();

}

}

});

}

}

使用Java Networking API

在Java联网API中,以下内容为对网络连接有用的各种包。

  • java.net.URL

  • java.net.URLConnection

    通过创建URL实例,指定互联网中资源的位置

URL url=new URL(“http://innovator.samsungmobile.com”);

然后使用URLConnection类进行读取或写入

URLConnection conn = url.openConnection();

接着读取已检索的响应

BufferedReader rd = new BufferedReader

(new InputStreamReader(response.getEntity().getContent()));

String line = "";

while ((line = rd.readLine()) != null) {

System.out.println(line);

}

示例

以下提供内容为可使用Java.net包来进行网络连接的示例代码片段。

添加许可“android.permission.INTERNET”至"AndroidManifest.xml"中,从而可允许你的应用程序访问网络。

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>

<manifest xmlns:android="http://schemas.android.com/apk/res/android"

package="com.net"

android:versionCode="1"

android:versionName="1.0">

<uses-sdk android:minSdkVersion="8" />

<uses-permission android:name="android.permission.INTERNET"></uses-permission>

<application android:icon="@drawable/icon" android:label="@string/app_name">

<activity android:name=".NetworkingProject" 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>

借助"NetworkingProject"活动创建"com.net"项目, 改变布局"main.xml",如下所示

Main.xml

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

android:orientation="vertical"

android:layout_width="fill_parent"

android:layout_height="fill_parent"

>

<TextView

android:text="Enter URL"

android:id="@+id/textView1"

android:layout_width="wrap_content"

android:layout_height="wrap_content">

</TextView>

<EditText

android:id="@+id/editText1"

android:layout_width="match_parent"

android:text="http://innovator.samsungmobile.com"

android:layout_height="wrap_content">

</EditText>

<Button

android:text="Click Here"

android:id="@+id/button1"

android:layout_width="wrap_content"

android:layout_height="wrap_content">

</Button>

<EditText

android:id="@+id/editText2"

android:layout_width="match_parent"

android:layout_height="fill_parent">

</EditText>

</LinearLayout>

现在创建可实现查看HTML代码的java程序。

NetworkingProject.java

package com.net;

import java.io.BufferedReader;

import java.io.InputStreamReader;

import java.net.URL;

import java.net.URLConnection;

import android.app.Activity;

import android.os.Bundle;

import android.view.View;

import android.view.View.OnClickListener;

import android.widget.Button;

import android.widget.TextView;

public class NetworkingProject extends Activity {

Button bt;

TextView textView1;

TextView textView2;

/** Called when the activity is first created. */

@Override

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.main);

bt = (Button) findViewById(R.id.button1);

textView1 = (TextView) findViewById(R.id.editText1);

textView2 = (TextView) findViewById(R.id.editText2);

bt.setOnClickListener(new OnClickListener() {

@Override

public void onClick(View v) {

// TODO Auto-generated method stub

textView2.setText("");

try {

/*Java Networking API*/

URL url = new URL(textView1.getText().toString());

URLConnection conn = url.openConnection();

/*Read the Response*/

BufferedReader rd = new BufferedReader(new

InputStreamReader(conn.getInputStream()));

String line = "";

while ((line = rd.readLine()) != null) {

textView2.append(line);

}

} catch (Exception exe) {

exe.printStackTrace();

}

}

});

}

}

输出结果

下图显示了以上示例程序的输出结果

(责任编辑:刘皓)
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics