2-5.url通信

                       三.URL通信)(url就是网络地址,俗称网址)
原理:
(1)根据指定的url创建URL对象
URL myurl=new URL(String spec);
(2)调用URLConnection.openConnection()方法打开连接
URLConnection uConn=myurl.openConnection();
(3)获得输入流
InputStream in=uConn.getInputStream();
(4)将网络信息提取并显示出来
例子:
(3-1)新建项目URL,添加一个按钮,单击可获得网络图片,添加一个ImageView显示获得图片
(3-2)在URLActivity中为按钮添加单击事件
try{
	//创建url
URL myurl=new URL("http://www.baidu.com/baidu_sylogol.gif");
//打开连接
URLConnection ucoo=myurl.openConnection();
InputStream in=ucoo.getInputStream();
//创建Bitmap
Bitmap bitmap=BitmapFactory.decodeStream(in);
image=(ImageView)findViewById(T,id,imageView);
image.setImageBitmap(bitmap);
}catch(IOException e){
}
(3-3)在onCreate()方法中添加如下代码,防止抛出网络异常
//设置线程政策
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
.detectDiskWrites()
.detectDiskReaders()
.detectNetwork()
.penaltyLog()
.build());
//设置虚拟内存政策
StrictMode.setVmPolicy(new StrickMode.VmPolicy.Builder()
.detectLeakedSqlLiteObjects()
.detectLeakedClosableObjects()
.penaltyLog()
.penaltyDeath()
.build());

(3-4)在AndroidMenifest.xml文件中添加用户权限,运行应用程序访问网络
<uses-permission:name="android.permission.INTERNET"/>

(3-5)运行结果

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值