android多线程之AsyncTask

来源:互联网 发布:微软远程控制软件 编辑:程序博客网 时间:2024/06/06 18:57

线程的概念
在程序开启后,就会有一个主线程,负责与用户交互。如果在主线程中执行了耗时操作,那么界面就会停止响应,所以要将耗时操作转移到别的线程中。


人们在设计躲到程序os时,引入了进程的概念,从而解决了在但处理器环境下的程序并发执行的问题,一直是以进程作为能拥有资源和独立调度(运行)的基本单位。人们又提出比进程更小的基本单位-线程的概念。


创建了一个线程,这个将不会出现阻塞的状态:

@Override
public void onClick(View arg0) {
new Thread(){
public void run(){
while(true){
try {
sleep(1000);
System.out.println("dddddddddddddddddddd");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
}.start();
}
单独的一个sleep(1000)将会是主线程进行阻塞。





主线程只负责和用户交互:

public void onClick(View v) {
try {
Thread.sleep(5000);

                                        //主线程界面就会停止响应,停止5秒
Toast.makeText(MainActivity.this, "我等了5秒", Toast.LENGTH_LONG).show();

} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

其他的线程负责耗时:

public void onClick(View v) {
new Thread(){
public void run(){
try {
while(true){
sleep(3000);
System.out.println("--------");
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}.start();
}
});

android多线程之AsyncTask:

package com.example.testasynctask;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;


import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;


public class MainActivity extends Activity {
    TextView  text;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text=(TextView) findViewById(R.id.textView1);
findViewById(R.id.read).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
       ReadURL("http://www.baidu.com");
}
});
}
private void ReadURL(String url) {
new AsyncTask<String, Float, String>(){
@Override
protected String doInBackground(String... arg0) {
   try {
   
URL url=new URL(arg0[0]);
URLConnection connection=url.openConnection();
long total=connection.getContentLength();
InputStream iStream=connection.getInputStream();
InputStreamReader isr=new InputStreamReader(iStream);
BufferedReader br=new BufferedReader(isr);
String line;
StringBuilder builder=new StringBuilder();
while((line=br.readLine())!=null){
builder.append(line);
publishProgress((float)builder.toString().length()/total);
}
br.close();
iStream.close();
return builder.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}


@Override
protected void onCancelled() {
super.onCancelled();
}


@Override
protected void onCancelled(String result) {
super.onCancelled(result);
}


@Override
protected void onPreExecute() {
Toast.makeText(MainActivity.this, "onPreExecute", Toast.LENGTH_LONG).show();
super.onPreExecute();
}


@Override
protected void onPostExecute(String result) {
//return builder.toString();
text.setText(result);
super.onPostExecute(result);
}
@Override
protected void onProgressUpdate(Float... values) {
Toast.makeText(MainActivity.this, values[0].toString(), Toast.LENGTH_LONG).show();
}

}.execute(url);
}

}






----------------------------------------------------------------------------------------------------------------------------------------------------------

package com.example.jsonread;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;


import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;


import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;


public class MainActivity extends Activity {
TextView text;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text=(TextView) findViewById(R.id.tv);
findViewById(R.id.button1).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
ReadUrl("http://www.baidu.com");
}
});
}
private void ReadUrl(String url) {
new AsyncTask<String, Float, String>(){


@Override
protected String doInBackground(String... arg0) {
try {
URL url=new URL(arg0[0]);

   URLConnection connection=url.openConnection();
   InputStream inStream=connection.getInputStream();
   InputStreamReader isr=new InputStreamReader(inStream);
   BufferedReader br=new BufferedReader(isr);
   String line;
   StringBuilder builder=new StringBuilder();
   while((line=br.readLine())!=null){
    builder.append(line);
    publishProgress((float)builder.toString().length()/connection.getContentLength());
   }
   br.close();
   inStream.close();
   return builder.toString();
} catch (MalformedURLException e) {

} catch (IOException e) {

}
return null;

}


@Override
protected void onCancelled() {
// TODO Auto-generated method stub
super.onCancelled();
}


@Override
protected void onCancelled(String result) {
// TODO Auto-generated method stub
super.onCancelled(result);
}


@Override
protected void onPostExecute(String result) {
text.setText(result);
super.onPostExecute(result);
}



@Override
protected void onPreExecute() {
Toast.makeText(MainActivity.this, "开始读入!", Toast.LENGTH_LONG).show();
super.onPreExecute();
}
            //对外发布的进度
//new AsyncTask<String, Void, String>(){


@Override
protected void onProgressUpdate(Float... values) {
Toast.makeText(MainActivity.this, values[0].toString(), Toast.LENGTH_LONG).show();
super.onProgressUpdate(values);
}

}.execute(url);

}
}

0 0
原创粉丝点击