Android连接网络
一、所需权限:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
二、关键方法
public class HttpExampleActivity extends Activity {private static final String DEBUG_TAG = "HttpExample";private EditText urlText;private TextView textView;@Overridepublic 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 {@Overrideprotected 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.@Overrideprotected void onPostExecute(String result) {textView.setText(result);}// 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 queryconn.connect();int response = conn.getResponseCode();Log.d(DEBUG_TAG, "The response is: " + response);is = conn.getInputStream();// Convert the InputStream into a stringString 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();}}}// 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);}}...
}
Android连接网络相关推荐
- Android连接网络立即同步时区
1.frameworks/base/services/core/java/com/android/server/NetworkTimeUpdateService.java private void o ...
- Android开发之根据Service的生命周期特点后台连接网络下载图片(源代码分享)
上一章讲到Service在后台启动后不会自动销毁掉,其销毁的方式有两种一个是在外部使用stopService()方法,一个就是在继承Service的类下调用stopSelf(),那么应该何时调用sto ...
- android 检查网络连接状态实现步骤
android 如何检查网络连接状态,是android开发中一个常见的问题,本文将介绍如何实现,需要的朋友可以参考下 获取网络信息需要在AndroidManifest.xml文件中加入相应的权限 ...
- 安卓ssr无网络连接_解决Android模拟器网络问题(使用了代理的情况下)
没错,又是AS的网络问题,而且又是代理的问题,真是不省心呐!! 最近在做curl移植到Android JNI的工作,老是出现 CURLE_PARTIAL_FILE 错误. 用Wireshark抓包居然 ...
- android 网络连接 网络是否可用,Android 使用ping判断网络/WIFI连接是否可用
最近项目中有一个网络判断的需求,因为终端只能连接wifi,wifi即使连接上也可能会出现不能连接网络的问题,所以需要进行网络连接的判断. ping的相关知识 使用ping检验网络是否可以连接 ping ...
- android不能在主线程,android.os.NetworkOnMainThreadException 在4.0之后谷歌强制要求连接网络不能在主线程进行访问(示例代码)...
谷歌在4.0系统以后就禁止在主线程中进行网络访问了,原因是: 主线程是负责UI的响应,如果在主线程进行网络访问,超过5秒的话就会引发强制关闭, 所以这种耗时的操作不能放在主线程里.放在子线程里,而子线 ...
- android计算汇率代码,android studio 开发实例 连接网络获取汇率
配置文件 AndroidManifest.xml 如下 Version:1.0StartHTML:000000243 EndHTML:000019067 StartFragment:000007811 ...
- android无网络状态栏,Android中检查网络连接状态的变化,无网络时跳转到设置界面...
在AndroidManifest.xml中加一个声明 1. 2. 3. 4. 5. NetCheckReceive.java文件如下 1.import android.content.Broadcas ...
- 第十一篇 ANDROID 系统网络连接和管理机制与架构
一 网络连接功能介绍 ANDROID 系统网络连接和管理服务由四个系统服务ConnectivityService.NetworkPolicyManagerService.NetworkManagem ...
最新文章
- 正余弦定理解三角形习题
- 分布式系统架构设计系列文章
- 怎么进入python官网-Python的安装及简单的使用
- Java程序员必备:序列化全方位解析
- 我们应该搞清楚分支预测
- java jdbc mysql url_java – 如何生成JDBC数据库URL?
- 项目class第十四周项目一:动物学叫
- 七阶拉丁方阵_【C语言】输出N阶拉丁方阵并统计个数
- [VB]BMP转JPG
- [Lisp]slime
- Linux服务器挂载ntfs移动硬盘
- Feature selection using SelectFromModel
- 小程序-仿微信通讯录-字母导航
- 信息可视化中的重要准则——以扇贝单词app中的可视化为例
- 纵行科技联合Kinéis等欧洲企业,开发ZETA星地融合低功耗物联网芯片
- 淘宝API upload_img - 上传图片到淘宝
- 什么是物联网?这里有你需要了解的一切
- 【游戏建模全流程】Maya风格化模型制作教程
- 二次规划问题的KKT 条件求解方法
- linux系统cpu性能测试工具