Android网络编程1
2016-07-20 10:51
393 查看
最近在自学Android开发,从这篇开始作为我学习android开发的笔记,来记录学习过程中遇到的问题点和其解决的方法;
Ui界面代码
界面后台代码
程序报错
07-2002:30:00.36115820-15820/com.example.lidezhen.myapplicationE/错误:android.os.NetworkOnMainThreadException
错误原因:Android在4.0之前的版本支持在主线程中访问网络,但是在4.0以后对这部分程序进行了优化,也就是说访问网络的代码不能写在主线程中了(我的虚拟机是android6.0的)
错误解决方法1:
在onCreate方法中添加如下代码
方法2:在点击事件里面添加多线程
程序执行成功
这样开新线程后程序还是报错
07-2002:49:12.20332712-707/com.example.lidezhen.myapplicationE/错误:android.view.ViewRootImpl$CalledFromWrongThreadException:Onlytheoriginalthreadthatcreatedaviewhierarchycantouchitsviews.
意思就是新的线程不能操作界面控件
解决方法:添加handeler
这样就不会再报异常
Ui界面代码
<?xmlversion="1.0"encoding="utf-8"?> <LinearLayoutxmlns: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:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context="com.example.lidezhen.myapplication.MainActivity" android:orientation="vertical"> <EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/text1" android:hint="请是输入网址"/> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="打开" android:onClick="Onclick"/> <TextView android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/tv1" android:hint="这是源码"/> </LinearLayout>
界面后台代码
packagecom.example.lidezhen.myapplication; importandroid.os.Bundle; importandroid.support.v7.app.AppCompatActivity; importandroid.util.Log; importandroid.view.View; importandroid.widget.EditText; importandroid.widget.TextView; importjava.io.ByteArrayOutputStream; importjava.io.InputStream; importjava.net.HttpURLConnection; importjava.net.URL; publicclassMainActivityextendsAppCompatActivity{ EditTextet; TextViewtv; @Override protectedvoidonCreate(BundlesavedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); et=(EditText)findViewById(R.id.text1); tv=(TextView)findViewById(R.id.tv1); //if(android.os.Build.VERSION.SDK_INT>9){ //StrictMode.ThreadPolicypolicy=newStrictMode.ThreadPolicy.Builder().permitAll().build(); //StrictMode.setThreadPolicy(policy); //} } publicvoidOnclick(Viewv) { try{ Stringpath=et.getText().toString(); URLurl=newURL(path); HttpURLConnectioncon=(HttpURLConnection)url.openConnection(); intcode=con.getResponseCode(); if(code==200) { InputStreamstream=con.getInputStream(); ByteArrayOutputStreamos=newByteArrayOutputStream(); intlen=-1; byte[]buff=newbyte[1024]; while((len=stream.read(buff))!=-1) { os.write(buff,0,len); } tv.setText(os.toString()); } }catch(Exceptione){ Log.e("错误",e.toString()); } } }编译并执行程序
程序报错
07-2002:30:00.36115820-15820/com.example.lidezhen.myapplicationE/错误:android.os.NetworkOnMainThreadException
错误原因:Android在4.0之前的版本支持在主线程中访问网络,但是在4.0以后对这部分程序进行了优化,也就是说访问网络的代码不能写在主线程中了(我的虚拟机是android6.0的)
错误解决方法1:
在onCreate方法中添加如下代码
if(android.os.Build.VERSION.SDK_INT>9){
StrictMode.ThreadPolicypolicy=newStrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
方法2:在点击事件里面添加多线程
publicvoidOnclick(Viewv)
{
newThread(){
@Override
publicvoidrun(){
try{
Stringpath=et.getText().toString();
URLurl=newURL(path);
HttpURLConnectioncon=(HttpURLConnection)url.openConnection();
intcode=con.getResponseCode();
if(code==200)
{
InputStreamstream=con.getInputStream();
ByteArrayOutputStreamos=newByteArrayOutputStream();
intlen=-1;
byte[]buff=newbyte[1024];
while((len=stream.read(buff))!=-1)
{
os.write(buff,0,len);
}
tv.setText(os.toString());
}
}catch(Exceptione){
Log.e("错误",e.toString());
}
}
}.start();
程序执行成功
这样开新线程后程序还是报错
07-2002:49:12.20332712-707/com.example.lidezhen.myapplicationE/错误:android.view.ViewRootImpl$CalledFromWrongThreadException:Onlytheoriginalthreadthatcreatedaviewhierarchycantouchitsviews.
意思就是新的线程不能操作界面控件
解决方法:添加handeler
packagecom.example.lidezhen.myapplication;
importandroid.os.Bundle;
importandroid.os.Handler;
importandroid.os.Message;
importandroid.support.v7.app.AppCompatActivity;
importandroid.util.Log;
importandroid.view.View;
importandroid.widget.EditText;
importandroid.widget.TextView;
importjava.io.ByteArrayOutputStream;
importjava.io.InputStream;
importjava.net.HttpURLConnection;
importjava.net.URL;
publicclassMainActivityextendsAppCompatActivity{
EditTextet;
TextViewtv;
@Override
protectedvoidonCreate(BundlesavedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et=(EditText)findViewById(R.id.text1);
tv=(TextView)findViewById(R.id.tv1);
//if(android.os.Build.VERSION.SDK_INT>9){
//StrictMode.ThreadPolicypolicy=newStrictMode.ThreadPolicy.Builder().permitAll().build();
//StrictMode.setThreadPolicy(policy);
//}
}
publicvoidOnclick(Viewv)
{
newThread(){
@Override
publicvoidrun(){
try{
Stringpath=et.getText().toString();
URLurl=newURL(path);
HttpURLConnectioncon=(HttpURLConnection)url.openConnection();
intcode=con.getResponseCode();
if(code==200)
{
InputStreamstream=con.getInputStream();
ByteArrayOutputStreamos=newByteArrayOutputStream();
intlen=-1;
byte[]buff=newbyte[1024];
while((len=stream.read(buff))!=-1)
{
os.write(buff,0,len);
}
//tv.setText(os.toString());
Messagemsg=newMessage();
msg.obj=os.toString();
handler.sendMessage(msg);
}
}catch(Exceptione){
Log.e("错误",e.toString());
}
}
}.start();
}
Handlerhandler=newHandler(){
publicvoidhandleMessage(Messagemsg){
Strings=(String)msg.obj;
tv.setText(s);
}
};
}
这样就不会再报异常
相关文章推荐
- TCP连接复用
- Netty精粹之TCP粘包拆包问题
- 使用Picasso进行网络图片的加载
- Linux基础网络配置以及常用的网络命令
- Android HTTP网络请求的异步实现
- Android中贼好用的网络框架----OkHttp
- TCP的3次握手和4次挥手
- loadrunner访问https后端服务
- TCP的3次握手和4次挥手
- 在c#中get同步访问http
- 使用HttpClient4.5 PoolingHttpClientConnectionManager 提交Http请求
- UNIX网络编程笔记(9)—守护进程和inetd超级服务器
- MVC发布到IIS,出现HTTP 错误 404.0 - Not Found的解决方法
- android studio 使用android-async-http
- 关于网络编程中MTU、TCP、UDP优化配置的一些总结
- 测试python HTTPServer功能
- 遭受ARP攻击后现象
- Java网络编程,Socket,ServerSocket使用,TCP,UDP的异同
- http://www.cnblogs.com/xdp-gacl/p/3902537.html
- TCP/IP详解学习笔记(5)-IP选路,动态选路,和一些细节