http请求图片
UI停止刷新,应用无法响应用户操作 耗时操作不应该在主线程进行 ANR
application not responding 应用无响应异常 主线程阻塞时间过长,就会抛出ANR 主线程又称UI线程,因为只有在主线程中,才能刷新UI
消息队列机制
消息队列机制 主线程创建时,系统会同时创建消息队列对象(MessageQueue)和消息轮询器对象(Looper) 轮询器的作用,就是不停的检测消息队列中是否有消息(Message) 消息队列一旦有消息,轮询器会把消息对象传给消息处理器(Handler),处理器会调用handleMessage方法来处理这条消息,handleMessage方法运行在主线程中,所以可以刷新ui 总结:只要消息队列有消息,handleMessage方法就会调用 子线程如果需要刷新ui,只需要往消息队列中发一条消息,触发handleMessage方法即可 子线程使用处理器对象的sendMessage方法发送消息
public class MainActivity extends Activity {
static ImageView iv;
static MainActivity ma;
static Handler handler = new Handler(){
public void handleMessage (android.os.Message msg) {
switch (msg.what) {
case 1 :
iv.setImageBitmap((Bitmap)msg.obj);
break ;
case 0 :
Toast.makeText(ma, "ÇëÇóʧ°Ü" , 0 ).show();
break ;
}
}
};
@Override
protected void onCreate (Bundle savedInstanceState) {
super .onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
iv = (ImageView) findViewById(R.id.iv);
ma = this ;
}
public void click (View v){
Thread t = new Thread(){
@Override
public void run () {
String path = "http://192.168.13.13:8080/dd.jpg" ;
try {
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET" );
conn.setConnectTimeout(5000 );
conn.setReadTimeout(5000 );
conn.connect();
if (conn.getResponseCode() == 200 ){
InputStream is = conn.getInputStream();
Bitmap bm = BitmapFactory.decodeStream(is);
Message msg = handler.obtainMessage();
msg.obj = bm;
msg.what = 1 ;
handler.sendMessage(msg);
} else {
Message msg = handler.obtainMessage();
msg.what = 0 ;
handler.sendMessage(msg);
}
} catch (Exception e) {
e.printStackTrace();
}
}
};
t.start();
}
}
新闻客户端显示列子代码
public class MainActivity extends Activity {
List<News> newsList;
Handler handler = new Handler(){
public void handleMessage (android.os.Message msg) {
ListView lv = (ListView) findViewById(R.id.lv);
lv.setAdapter(new MyAdapter());
}
};
@Override
protected void onCreate (Bundle savedInstanceState) {
super .onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getNewsInfo();
}
class MyAdapter extends BaseAdapter{
@Override
public int getCount () {
return newsList.size();
}
@Override
public View getView (int position, View convertView, ViewGroup parent) {
News news = newsList.get(position);
View v = null ;
ViewHolder mHolder;
if (convertView == null ) {
v = View.inflate(MainActivity.this , R.layout.item_listview, null );
mHolder = new ViewHolder();
mHolder.tv_title = (TextView) v.findViewById(R.id.tv_title);
mHolder.tv_detail = (TextView) v.findViewById(R.id.tv_detail);
mHolder.tv_comment = (TextView) v.findViewById(R.id.tv_comment);
mHolder.siv = (SmartImageView) v.findViewById(R.id.iv);
v.setTag(mHolder);
} else {
v = convertView;
mHolder = (ViewHolder) v.getTag();
}
mHolder.tv_title.setText(news.getTitle());
mHolder.tv_detail.setText(news.getDetail());
mHolder.tv_comment.setText(news.getComment() + "" );
mHolder.siv.setImageUrl(news.getImageUrl());
return v;
}
class ViewHolder {
TextView tv_title;
TextView tv_detail;
TextView tv_comment;
SmartImageView siv;
}
@Override
public Object getItem (int position) {
return null ;
}
@Override
public long getItemId (int position) {
return 0 ;
}
}
private void getNewsInfo () {
Thread t = new Thread(){
@Override
public void run () {
String path = "http://192.168.13.13:8080/news.xml" ;
try {
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET" );
conn.setConnectTimeout(5000 );
conn.setReadTimeout(5000 );
if (conn.getResponseCode() == 200 ){
InputStream is = conn.getInputStream();
parseNewsXml(is);
}
} catch (Exception e) {
e.printStackTrace();
}
}
};
t.start();
}
private void parseNewsXml (InputStream is) {
XmlPullParser xp = Xml.newPullParser();
try {
xp.setInput(is, "utf-8" );
int type = xp.getEventType();
News news = null ;
while (type != XmlPullParser.END_DOCUMENT){
switch (type) {
case XmlPullParser.START_TAG:
if ("newslist" .equals(xp.getName())){
newsList = new ArrayList<News>();
}
else if ("news" .equals(xp.getName())){
news = new News();
}
else if ("title" .equals(xp.getName())){
String title = xp.nextText();
news.setTitle(title);
}
else if ("detail" .equals(xp.getName())){
String detail = xp.nextText();
news.setDetail(detail);
}
else if ("comment" .equals(xp.getName())){
String comment = xp.nextText();
news.setComment(comment);
}
else if ("image" .equals(xp.getName())){
String image = xp.nextText();
news.setImageUrl(image);
}
break ;
case XmlPullParser.END_TAG:
if ("news" .equals(xp.getName())){
newsList.add(news);
}
break ;
}
type = xp.next();
}
handler.sendEmptyMessage(1 );
} catch (Exception e) {
e.printStackTrace();
}
}
}
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android ="http://schemas.android.com/apk/res/android"
android:layout_width ="match_parent"
android:layout_height ="wrap_content" >
<com.loopj.android.image.SmartImageView
android:id ="@+id/iv"
android:layout_width ="90dp"
android:layout_height ="70dp"
android:src ="@drawable/ic_launcher"
android:layout_centerVertical ="true"
/>
<TextView
android:id ="@+id/tv_title"
android:layout_width ="match_parent"
android:layout_height ="wrap_content"
android:text ="这是大标题志哥教你上塑料adasfsadfdsfdsgsd"
android:layout_toRightOf ="@id/iv"
android:textSize ="22sp"
android:singleLine ="true"
/>
<TextView
android:id ="@+id/tv_detail"
android:layout_width ="match_parent"
android:layout_height ="wrap_content"
android:text ="这是正文志哥教你带崩三路adasfsadasdasdasdasidhsakjhdkjashdkjahskjdhsakjdfdsfdsgsd"
android:layout_toRightOf ="@id/iv"
android:layout_below ="@id/tv_title"
android:textSize ="15sp"
android:textColor ="@android:color/darker_gray"
android:lines ="2"
/>
<TextView
android:id ="@+id/tv_comment"
android:layout_width ="wrap_content"
android:layout_height ="wrap_content"
android:text ="65031条评论"
android:textColor ="#ff0000"
android:layout_alignParentRight ="true"
android:layout_below ="@id/tv_detail"
/>
</RelativeLayout >
使用http get方式提交数据
public class MainActivity extends Activity {
@Override
protected void onCreate (Bundle savedInstanceState) {
super .onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
Handler handler = new Handler(){
public void handleMessage (android.os.Message msg) {
Toast.makeText(MainActivity.this , (String)msg.obj, 0 ).show();
}
};
public void click (View v){
EditText et_name = (EditText) findViewById(R.id.et_name);
EditText et_pass = (EditText) findViewById(R.id.et_pass);
final String name = et_name.getText().toString();
final String pass = et_pass.getText().toString();
Thread t = new Thread(){
@Override
public void run () {
@SuppressWarnings ("deprecation" )
String path = "http://192.168.13.13/Web2/servlet/LoginServlet?name=" + URLEncoder.encode(name) + "&pass=" + pass;
try {
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET" );
conn.setConnectTimeout(5000 );
conn.setReadTimeout(5000 );
if (conn.getResponseCode() == 200 ){
InputStream is =conn.getInputStream();
String text = Utils.getTextFromStream(is);
Message msg = handler.obtainMessage();
msg.obj = text;
handler.sendMessage(msg);
}
} catch (Exception e) {
e.printStackTrace();
}
}
};
t.start();
}
}
使用http post方式提交数据
public class MainActivity extends Activity {
@Override
protected void onCreate (Bundle savedInstanceState) {
super .onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
Handler handler = new Handler(){
public void handleMessage (android.os.Message msg) {
Toast.makeText(MainActivity.this , (String)msg.obj, 0 ).show();
}
};
public void click (View v){
EditText et_name = (EditText) findViewById(R.id.et_name);
EditText et_pass = (EditText) findViewById(R.id.et_pass);
final String name = et_name.getText().toString();
final String pass = et_pass.getText().toString();
Thread t = new Thread(){
@Override
public void run () {
@SuppressWarnings ("deprecation" )
String path = "http://192.168.13.13/Web2/servlet/LoginServlet" ;
try {
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST" );
conn.setConnectTimeout(5000 );
conn.setReadTimeout(5000 );
String data = "name=" + URLEncoder.encode(name) + "&pass=" + pass;
conn.setRequestProperty("Content-Type" , "application/x-www-form-urlencoded" );
conn.setRequestProperty("Content-Length" , data.length() + "" );
conn.setDoOutput(true );
OutputStream os = conn.getOutputStream();
os.write(data.getBytes());
if (conn.getResponseCode() == 200 ){
InputStream is = conn.getInputStream();
String text = Utils.getTextFromStream(is);
Message msg = handler.obtainMessage();
msg.obj = text;
handler.sendMessage(msg);
}
} catch (Exception e) {
e.printStackTrace();
}
}
};
t.start();
}
}