Connecting to the Network [连接到网络]
- 这一课会演示如何实现一个简单的连接到网络的程序。它提供了一些你应该follow的最好示例,用来创建最简单的网络连接程序。
- 请注意,想要执行网络操作首先需要在程序的manifest文件中添加下面的permissions:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Choose an HTTP Client [选择一个HTTP Client]
大多数连接网络的Android app会使用HTTP来发送与接受数据。Android提供了两种HTTP clients:HttpURLConnection
与ApacheHttpClient。
他们二者均支持HTTPS
,都以流方式进行上传与下载,都有可配置的timeout, IPv6 与连接池(connection pooling).
我们推荐从Gingerbread版本开始使用HttpURLConnection
。关于这部分的更多详情,请参考Android's
HTTP Clients。
Check the Network Connection [检测网络连接]
在你的app尝试进行网络连接之前,需要检测当前是否有可用的网络。请注意,设备可能会不在网络覆盖范围内,或者用户可能关闭Wi-Fi与移动网络连接。关于这方面更多的资料,请参考:Managing Network Usage.[下一课内容]
public void myClickHandler(View view) {
...
ConnectivityManager connMgr = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
// fetch data
} else {
// display error
}
...
}
Perform Network Operations on a Separate Thread [在另外一个Thread执行网络操作]
- 网络操作会遇到不可预期的延迟。显然为了避免一个不好的用户体验,总是在UI Thread之外去执行网络操作。
AsyncTask
类提供了一种简单的方式来处理这个问题。关于更多的详情,请参考:Multithreading
For Performance. [唉,打不开]
- 在下面的代码示例中,
myClickHandler()
方法会触发一个新的DownloadWebpageTask().execute(stringUrl)
. 它继承自AsyncTask,实现了下面两个方法:
public class HttpExampleActivity extends Activity {
private static final String DEBUG_TAG = "HttpExample";
private EditText urlText;
private TextView textView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
urlText = (EditText) findViewById(R.id.myUrl);
textView = (TextView) findViewById(R.id.myText);
}
// When user clicks button, calls AsyncTask.
// Before attempting to fetch the URL, makes sure that there is a network connection.
public void myClickHandler(View view) {
// Gets the URL from the UI's text field.
String stringUrl = urlText.getText().toString();
ConnectivityManager connMgr = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
new DownloadWebpageText().execute(stringUrl);
} else {
textView.setText("No network connection available.");
}
}
// Uses AsyncTask to create a task away from the main UI thread. This task takes a
// URL string and uses it to create an HttpUrlConnection. Once the connection
// has been established, the AsyncTask downloads the contents of the webpage as
// an InputStream. Finally, the InputStream is converted into a string, which is
// displayed in the UI by the AsyncTask's onPostExecute method.
private class DownloadWebpageText extends AsyncTask {
@Override
protected String doInBackground(String... urls) {
// params comes from the execute() call: params[0] is the url.
try {
return downloadUrl(urls[0]);
} catch (IOException e) {
return "Unable to retrieve web page. URL may be invalid.";
}
}
// onPostExecute displays the results of the AsyncTask.
@Override
protected void onPostExecute(String result) {
textView.setText(result);
}
}
...
}
关于上面那段代码的示例详解,请参考下面:[就不翻译了,还比较简单,仔细看下上面的代码]
-
When users click the button that invokes
myClickHandler()
, the app passes the specified URL to theAsyncTask
subclassDownloadWebpageTask
.
-
The
AsyncTask
methoddoInBackground()
calls
thedownloadUrl()
method.
-
The
downloadUrl()
method takes a URL string as a parameter and uses it to create aURL
object.
-
The
URL
object is used to establish anHttpURLConnection
.
-
Once the connection has been established, the
HttpURLConnection
object fetches the web
page content as anInputStream
.
-
The
InputStream
is passed to thereadIt()
method,
which converts the stream to a string.
-
Finally, the
AsyncTask
'sonPostExecute()
method
displays the string in the main activity's UI.
Connect and Download Data [连接并下载数据]
// Given a URL, establishes an HttpUrlConnection and retrieves
// the web page content as a InputStream, which it returns as
// a string.
private String downloadUrl(String myurl) throws IOException {
InputStream is = null;
// Only display the first 500 characters of the retrieved
// web page content.
int len = 500;
try {
URL url = new URL(myurl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("GET");
conn.setDoInput(true);
// Starts the query
conn.connect();
int response = conn.getResponseCode();
Log.d(DEBUG_TAG, "The response is: " + response);
is = conn.getInputStream();
// Convert the InputStream into a string
String contentAsString = readIt(is, len);
return contentAsString;
// Makes sure that the InputStream is closed after the app is
// finished using it.
} finally {
if (is != null) {
is.close();
}
}
}
- 请注意,
getResponseCode()
会返回连接状态码(status code). 这是一种获知额外网络连接信息的有效方式。status code 是 200 则意味着连接成功.
Convert the InputStream to a String [把InputStream的数据转换为String]
InputStream is = null;
...
Bitmap bitmap = BitmapFactory.decodeStream(is);
ImageView imageView = (ImageView) findViewById(R.id.image_view);
imageView.setImageBitmap(bitmap);
// Reads an InputStream and converts it to a String.
public String readIt(InputStream stream, int len) throws IOException, UnsupportedEncodingException {
Reader reader = null;
reader = new InputStreamReader(stream, "UTF-8");
char[] buffer = new char[len];
reader.read(buffer);
return new String(buffer);
}
学习自:http://developer.android.com/training/basics/network-ops/connecting.html,请多指教,谢谢!
转载请注明出自:http://blog.csdn.net/kesenhoo,谢谢配合!
分享到:
相关推荐
Bumping基础培训资料-Bumping-Basic-Training-Material
1Fanuc-Robot-Basic-Training-FANUC机器人培训教材(基本).ppt该文档详细且完整,值得借鉴下载使用,欢迎下载使用,有问题可以第一时间联系作者~
Fanuc-Robot-Basic-Training-FANUC机器人培训教材(基本).ppt该文档详细且完整,值得借鉴下载使用,欢迎下载使用,有问题可以第一时间联系作者~
android-Camera2Basic-master
最新 instantclient-basic-linux.x64-11.2.0.4.0最新 instantclient-basic-linux.x64-11.2.0.4.0最新 instantclient-basic-linux.x64-11.2.0.4.0最新 instantclient-basic-linux.x64-11.2.0.4.0最新 instantclient-...
Google Play game services - Android Samples Copyright (C) 2014 Google Inc. Contents These are the Android samples for Google Play game services. BasicSamples - a set of basic samples, including a ...
instantclient-basic-nt-19.8.0.0.0dbru.zip(我电脑上用的是这个版本连接的Oracle11g) 3、配置window操作系统环境变量(新建以下两个变量) 此电脑(右键)→属性→高级系统设置→环境变量→系统环境变量→新建 ...
oracle-instantclient11.2-basic-11.2.0.4.0-1.x86_64.rpm --基础包,为了运行OCI、OCCI、JDBC-OCI 这几个应用程序; oracle-instantclient11.2-sqlplus-11.2.0.4.0-1.x86_64.rpm --补充包/文件,是为了运行sql*plus...
Version 12.2.0.1.0 Instant Client Package - Basic: All files required to run OCI, OCCI, and JDBC-OCI ...oracle-instantclient12.2-basiclite-12.2.0.1.0-1.x86_64.rpm (52,826,628 bytes) (cksum - 888077889)
instantclient-basic-nt-11.2.0.2.0
oracle 数据库驱动 instantclient-basic-windows.x64-12.2.0.1.0.zip 和 instantclient-basiclite-windows.x64-12.2.0.1.0.zip
spring-android-basic-auth
instantclient-basic-win-x86-64-11.1.0.7.0,oracle数据库连接oracle9i及以上版本
android-basic-samples Android Project的基本示例。 您可以在任何Android设备上运行。 执照 此内容根据MIT许可证( )发布。 版权所有(c)2015 Gilberto C Lupatini
android-Camera2Basic-master源码,是一个很不错的Android源码,有兴趣的伙伴们抽时间可以看一下把。
oracle 数据库驱动 instantclient-basiclite-windows.x64-12.2.0.1.0.zip
将 lib 目录下的 jmeter-plugins-cmn-jmeter-0.3.jar 拷贝到 %JMeter%/lib 目录下,将 ext 目录下的 jmeter-plugins-graphs-basic-2.0.jar 和 jmeter-plugins-manager-0.10.jar 拷贝到 %JMeter%/lib/ext 目录下,...
oracle-instantclient19.6-basic-19.6.0.0.0-1.x86_64.rpm oracle-instantclient19.6-devel-19.6.0.0.0-1.x86_64.rpm
下载对应版本instantclient-basic-win-x86-64-11.2.0.1.0.zip包 这里对应的也是64位的instantclient包,将其完全解压到Navicate Premium安装目录,删除原有的installclient_10_2文件夹,其中最关键的是此文件夹中的...
sudo alien -i /home/ubuntu/oracle-instantclient-basic-21.1.0.0.0-1.x86_64.rpm sudo alien -i /home/ubuntu/oracle-instantclient-devel-21.1.0.0.0-1.x86_64.rpm sudo alien -i /home/ubuntu/oracle-instant...