您的位置:首页 > 理论基础 > 计算机网络

Android网络编程1

2016-07-20 10:51 393 查看
最近在自学Android开发,从这篇开始作为我学习android开发的笔记,来记录学习过程中遇到的问题点和其解决的方法;

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);
}

};

}


这样就不会再报异常
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: