近几天,学长讲了一些关于json数据的知识,给我们布置了一个作业,尽管给了我们例子,但是对于我这种连线程是什么都不知道人来说,太困难了。
经过一天的奋战,终于对这些东西有所了解,handler,message,线程,下面通过android端得到源码为例,介绍两种线程方法。
方法一:
主Activity方法,
package com.example.work2;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.method.MovementMethod;
import android.text.method.ScrollingMovementMethod;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
private Button bt;
private EditText tv1;
private TextView tv2;
private String text1;
private String t;
@Override
//实例化控件
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bt=(Button) findViewById(R.id.button1);
//得到的是地址实例
tv1=(EditText) findViewById(R.id.et1);
tv2=(TextView) findViewById(R.id.tv2);
//不能在这里得到text1,因为还没有点击
//text1=tv1.getText().toString().trim();
//设置滚动
tv2.setMovementMethod(ScrollingMovementMethod.getInstance());
bt.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
text1=tv1.getText().toString().trim();
Toast.makeText(MainActivity.this, "编辑器里写的是:"+text1, Toast.LENGTH_SHORT).show();
new Thread(new MyThread()).start();
}
});
}
//返回子线城中的值,并在ui界面上操作
private Handler hander=new Handler(){
public void handleMessage(Message msg)
{
if(msg.what==1)
{
String response = (String)msg.obj;
//在这里进行操作,将结果显示到界面
tv2.setText(response);
}
}
};
//开启另一子线程
class MyThread implements Runnable
{
@Override
public void run() {
// TODO Auto-generated method stub
//将s包装成一个url对象
URL url;
try {
url = new URL(text1);
//获得链接对象
HttpURLConnection http = (HttpURLConnection) url.openConnection();
http.setConnectTimeout(5000);
//设置请求对象,setrequestMethod
http.setRequestMethod("GET");
//判断是否请求成功
if(http.getResponseCode()==200)
{
//得到一个流
InputStream input=http.getInputStream();
//从流中读取二进制数
// byte[] data =StreamTool.read(input);
// String data1 = new String(data,"utf-8");
// return data1;
//下面对获取的输入流进行读取
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
StringBuilder response = new StringBuilder();
String line;
while((line=reader.readLine())!=null)
{
response.append(line);
}
Message message = new Message();
message.what=1;
//将服务器返回的结果存放到Message中
message.obj=response.toString();
hander.sendMessage(message);
}
}catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
布局文件:
<RelativeLayout xmlns: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.work2.MainActivity" >
<EditText
android:id="@+id/et1"
android:layout_width="250dp"
android:layout_height="40dp"
/>
<Button
android:layout_toRightOf="@id/et1"
android:id="@+id/button1"
android:layout_width="match_parent"
android:layout_height="40dp"
android:text="Button" />
<TextView
android:layout_marginTop="10dp"
android:id="@+id/tv2"
android:layout_below="@id/et1"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</RelativeLayout>
方法二:
在一个类里实现子线程
package com.example.work1;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.method.ScrollingMovementMethod;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
private EditText path;
private Button button;
private TextView text;
public String t=null;
private Handler mHandler;//声明一个用于处理消息的Handler类的对象
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
path=(EditText)findViewById(R.id.path);
button=(Button)findViewById(R.id.ok);
text=(TextView)findViewById(R.id.text);
text.setMovementMethod(ScrollingMovementMethod.getInstance());
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
final String url=path.getText().toString();
Toast.makeText(MainActivity.this, "编辑器里写的是:"+url, Toast.LENGTH_SHORT).show();
Thread th=new Thread(){
@Override
public void run() {
try {
t=getHtml(url);
Message m=new Message();
if(t!=null){
m.what=0x111;
mHandler.sendMessage(m);//发送消息
}else{
m.what=0x110;
mHandler.sendMessage(m);//发送消息
return;
}
} catch (Exception e) {
e.printStackTrace();
}
}
};
th.start();
mHandler=new Handler(){
@Override
public void handleMessage(Message msg) {
if(msg.what==0x111){
text.setText(t);
}else{
Toast.makeText(MainActivity.this, "失败,请检查网络!", Toast.LENGTH_SHORT).show();
}
super.handleMessage(msg);
}
};
}
});
}
/*
* 获取网页html源代码:
* path 网页路径
* */
public static String getHtml(String path) throws Exception{
//将path包装成一个URL对象
URL url=new URL(path);
//取得链接对象(基于HTTP协议链接对象)
HttpURLConnection conn=(HttpURLConnection) url.openConnection();
//设置超时时间
conn.setConnectTimeout(5000);
//设置请求方式
conn.setRequestMethod("GET");
//判断请求是否成功(看一下getResponseCode)
if(conn.getResponseCode()==200){
InputStream instream=conn.getInputStream();
//流的工具类,专门从流中读取数据(返回的是二进制数据)
byte[] data=StreamTool.read(instream);
String html= new String(data,"UTF-8");
return html;
}
return null;
}
}
分步读取,一次1兆,提高安全性
package com.example.work1;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
public class StreamTool {
public static byte[] read(InputStream instream) throws Exception{
ByteArrayOutputStream outStream=new ByteArrayOutputStream();
//定义一个字节数组
byte[] buffer=new byte[1024];
//读满数组,就会返回(返回的是int型,代表读取的数组长度)
//当返回值为-1时说明已经读完
int len=0;
while((len = instream.read(buffer)) !=-1){
//buffer有多少数据就读多少
outStream.write(buffer, 0, len);
}
instream.close();
return outStream.toByteArray();
}
}
布局:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
tools:context="com.example.htmlview.MainActivity" >
<LinearLayout android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<EditText android:layout_width="100pt"
android:layout_height="wrap_content"
android:id="@+id/path"/>
<Button android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="确定"
android:id="@+id/ok"/>
</LinearLayout>
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="暂无信息"
android:scrollbars="vertical"
android:id="@+id/text"/>
</LinearLayout>
注意,最后别忘了设置联网