Android06-网络编程(一)

1.查看网页源码的案例

public class MainActivity extends Activity {

    private EditText et_url;
	private Button btn_show;
	private TextView tv_code;

	@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        et_url = (EditText) findViewById(R.id.et_url);
        btn_show = (Button) findViewById(R.id.btn_show);
        tv_code = (TextView) findViewById(R.id.tv_code);
        
        btn_show.setOnClickListener(new MyListener());
    }
	
	private class MyListener implements OnClickListener {

		@Override
		public void onClick(View v) {
			//获取EditText出入的url
			String path = et_url.getText().toString();
			System.out.println(path);
			try {
				URL url = new URL(path);
				//进行网络连接,获取HttpURLConnection
				HttpURLConnection connection = (HttpURLConnection) url.openConnection();
				//设置连接方式 默认GET
				connection.setRequestMethod("GET");
				//设置连接的超时时间
				connection.setConnectTimeout(10000);
				//获取响应码 200表示正常
				int code = connection.getResponseCode();
				if(code == 200){
					InputStream inputStream = connection.getInputStream();
					String result = Utils.getStringFromStream(inputStream);
					tv_code.setText(result);
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} 
		}
		
	}
}
public class Utils {

	/**
	 * 将InputStream的字符串取出
	 * @param inputStream
	 * @return
	 */
	public static String getStringFromStream(InputStream inputStream) {
		//ByteArrayOutputStream作为中间流进行缓冲,最后在转化为字节
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		//每次取出的字节,先存入bytes中,在写入ByteArrayOutputStream
		byte[] bytes = new byte[1024];
		int len  = -1;
		try {
			while((len = inputStream.read(bytes)) != -1){
				baos.write(bytes, 0, len);
			}
			byte[] byteArray = baos.toByteArray();
			return new String(byteArray);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		} finally {
			try {
				inputStream.close();
				baos.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}

2.网络服务所需要的权限

1:AndroidManifext.xml -> Permissions -> Add -> Uses Permission -> android.permission.INTERNET。
2:java.net.SocketException: socket failed: EACCES (Permission denied),表示没有相应的权限。

3.ScrollView实现滚动

 <ScrollView
     android:layout_below="@id/btn_show"
     android:layout_width="match_parent"
     android:layout_height="match_parent" >

     <LinearLayout
         android:layout_width="match_parent"
         android:layout_height="match_parent"
         android:orientation="vertical" >

         <Button
                 android:layout_width="wrap_content"
                 android:layout_height="wrap_content"
                 android:text="bnt"  />

         <TextView
                   android:id="@+id/tv_code"
                   android:layout_width="match_parent"
                   android:layout_height="match_parent" />
     </LinearLayout>
</ScrollView>
ScrollView中只能有一个子组件。

4.ANR问题

1:ANR问题,Application Not Responding,当主线程被阻塞一定的时间时会出现ANR问题,一般是5秒钟。
2:安卓4.0之前允许在主线程中进行网络的操作,网络经常会有延时,所以会出现ANR问题。
3:安卓4.0之后,不允许在主线程中进行网络操作,避免网络延时。要在子线程中进行操作,否则抛出android.os.NetworkOnMainThreadException。
4:在进行子线程操作网络的时候应该主要,子线程不能进行UI的修改,应该在主线程中进行UI的修改,所以主线程又叫UI线程。不能在子线程中进行UI的修改,是为了避免多个子线程同时进行UI的修改时,子线程之间的修改时间先后的问题。

5.消息机制的写法

1:在主线程中创建Handler对象,重写handlerMessage方法。
2:子线程中需要更新UI的地方,创建Message对象,通过message.obj携带数据。
3:通过Handler的sendMessage方法发送消息。
4:在重写之后的handlerMessage方法中更新UI。
public class MainActivity extends Activity {

    private EditText et_url;
	private Button btn_show;
	private TextView tv_code;
	//在主线程中创建Handler对象,通过Handler在主线程中处理消息
	private Handler handler = new Handler(){
		public void handleMessage(android.os.Message msg) {
			String result = (String) msg.obj;
			tv_code.setText(result);
		}
	};

	@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        et_url = (EditText) findViewById(R.id.et_url);
        btn_show = (Button) findViewById(R.id.btn_show);
        tv_code = (TextView) findViewById(R.id.tv_code);
        
        btn_show.setOnClickListener(new MyListener());
    }
	
	private class MyListener implements OnClickListener {

		@Override
		public void onClick(View v) {
			
			//不能在主线程中进行网络操作,所以在需要重新创建线程
			new Thread(){
				@Override
				public void run() {
					
					//获取EditText出入的url
					String path = et_url.getText().toString();
					System.out.println(path);
					try {
						URL url = new URL(path);
						//进行网络连接,获取HttpURLConnection
						HttpURLConnection connection = (HttpURLConnection) url.openConnection();
						//设置连接方式 默认GET
						connection.setRequestMethod("GET");
						//设置连接的超时时间
						connection.setConnectTimeout(10000);
						//获取响应码 200表示正常
						int code = connection.getResponseCode();
						if(code == 200){
							InputStream inputStream = connection.getInputStream();
							String result = Utils.getStringFromStream(inputStream);
							//子线程不能进行UI操作,所以需要使用Handler与主线程进行通信
							//将Message消息进行传递
							//Message message = new Message();
							//利用系统设计的消息池获取消息,可以起到消息的重用的作用
							Message message = Message.obtain();
							message.obj = result;
							handler.sendMessage(message);
						}
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} 
				}
			}.start();;
		}
	}
}

5.Handler的原理

1:Looper,轮询器,用来取出消息,于当前线程绑定在一起。
2:MessageQueue,消息队列,用来存储消息。
3:Handler,进行消息的处理。
4:Message,具体的消息。

6.图片查看器

public class MainActivity extends Activity implements OnClickListener {

    private EditText et_url;
	private Button btn_show;
	private ImageView iv_image;
	private Handler handler = new Handler(){
		
        //处理消息,为1时说明拿到图片,进行显示
		public void handleMessage(Message msg) {
			if(msg.what == 1){
				Bitmap bitmap = (Bitmap) msg.obj;
				iv_image.setImageBitmap(bitmap);
			}
		}
	};

	@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        et_url = (EditText) findViewById(R.id.et_url);
        btn_show = (Button) findViewById(R.id.btn_show);
        iv_image = (ImageView) findViewById(R.id.iv_image);
        
        et_url.setText("http://10.0.2.2:8080/tomcat.png");
        btn_show.setOnClickListener(this);
    }

	@Override
	public void onClick(View v) {
		
		new Thread(){
			@Override
			public void run() {
				
				try {
					URL url = new URL(et_url.getText().toString());
					HttpURLConnection connection = (HttpURLConnection) url.openConnection();
					connection.setRequestMethod("GET");
					connection.setConnectTimeout(10000);
					int code = connection.getResponseCode();
					if(code == 200){
						//进行图片的缓存
						Bitmap bitmap = BitmapFactory.decodeStream(connection.getInputStream());
						//从消息池获取消息
						Message message = Message.obtain();
						message.obj = bitmap;
						//区分不同类型的消息
						message.what = 1;
						handler.sendMessage(message);
					}else {
						Message message = Message.obtain();
						message.what = 2;
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}.start();
	}
}

7.Handler延时的操作

public class MainActivity extends Activity {
	
	private int count = 60;
	private Handler handler = new Handler(){
		public void handleMessage(Message msg) {
			count();
		}
	};
	private TextView tv_num;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        tv_num = (TextView) findViewById(R.id.tv_num);
        
        //通过handler.sendMessageDelayed方法进行操作的延时
//        Message message = Message.obtain();
//        handler.sendMessageDelayed(message, 1000);
        
        //不传递消息时使用sendEmptyMessageDelayed方法
        handler.sendEmptyMessageDelayed(1, 1000);
    }
    
    public void count(){
    	count--;
    	tv_num.setText(count + "");
    	
//    	Message message = Message.obtain();
//        handler.sendMessageDelayed(message, 1000);
    	
    	handler.sendEmptyMessageDelayed(1, 1000);
    }
}

8.runOnUiThread

//比较简单的业务,可以使用runOnUiThread保证其在主线程中执行
//其原理就是,在方法执行的时候,会进行判断,如果是主线程,就直接执行
//如果不是主线程,就是用Handler,让其在主线程中执行
runOnUiThread(new Runnable() {

    @Override
    public void run() {
        //这里的run方法一定会在主线程中执行
        Toast.makeText(MainActivity.this, "bad", Toast.LENGTH_LONG).show();
    }
});

9.新闻展示案例

<?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="match_parent"
    android:padding="5dp" >
    
	<!--  使用自定义的组件,要输入全路径名 -->
    <com.loopj.android.image.SmartImageView
        android:id="@+id/iv_icon"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_launcher" />
    
    <TextView
        android:id="@+id/tv_title"
        android:layout_toRightOf="@id/iv_icon"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="5dp"
        android:textSize="18sp"
        android:text="我是标题" />
    
    <TextView
        android:id="@+id/tv_content"
        android:layout_toRightOf="@id/iv_icon"
        android:layout_below="@id/tv_title"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="5dp"
        android:textSize="15sp"
        android:textColor="#88000000"
        android:text="我是标题的内容我是标题的内容我是标题的内容" />
    
    <TextView
        android:id="@+id/tv_comment"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_below="@id/tv_content"
        android:layout_marginTop="-18dp"
        android:text="200条评论" />
</RelativeLayout>
public class MainActivity extends Activity {
	
	private static final int GETDATA = 0;

    private ListView lv_list;
    private final String path = "http://192.168.43.21:8080/img/news.xml";
    private List<NewsItem> lists = new ArrayList<NewsItem>();
    private NewsItem newsItem = null;
    private Handler handler = new Handler(){
    	
    	public void handleMessage(Message msg) {
            //数据和View进行适配
    		lv_list.setAdapter(new MyAdapter());
    	}
    };

	@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        lv_list = (ListView) findViewById(R.id.lv_list);
        
        //初始化数据,从服务端获取数据
        initData();
    }
	
	private void initData(){
		
		//不在主线程中进行网络操作
		new Thread(){
			
			public void run() {
				try {
					URL url = new URL(path);
					//通过URL获取网络连接,并且设置连接的信息
					HttpURLConnection connection = (HttpURLConnection) url.openConnection();
					connection.setRequestMethod("GET");
					connection.setConnectTimeout(10000);
					int responseCode = connection.getResponseCode();
					//200 成功获取数据
					if(responseCode == 200){
						//将HttpURLConnection连接获取的数据通过流转换为XML,并进行数据的解析
						XmlPullParser xmlPullParser = Xml.newPullParser();
						xmlPullParser.setInput(connection.getInputStream(), "utf-8");
						int eventType = xmlPullParser.getEventType();
						while(eventType != XmlPullParser.END_DOCUMENT){
							
							switch (eventType) {
							case XmlPullParser.START_TAG:
								
								if("item".equals(xmlPullParser.getName())){
									newsItem = new NewsItem();
								}else if("description".equals(xmlPullParser.getName())){
									newsItem.description = xmlPullParser.nextText();
								}else if("image".equals(xmlPullParser.getName())){
									newsItem.image = xmlPullParser.nextText();
								}else if("type".equals(xmlPullParser.getName())){
									newsItem.type = xmlPullParser.nextText();
								}else if("comment".equals(xmlPullParser.getName())){
									newsItem.comment = xmlPullParser.nextText();
								}else if("title".equals(xmlPullParser.getName())){
									newsItem.title = xmlPullParser.nextText();
								}
								break;

							case XmlPullParser.END_TAG:
								if("item".equals(xmlPullParser.getName())){
									lists.add(newsItem);
								}
								break;
							}
							
							eventType = xmlPullParser.next();
						}
						
						
					}
					//子线程不改变UI,所以在数据加载完成之后,通知主线程改变UI
					handler.sendEmptyMessage(GETDATA);
					
				} catch (Exception e) {
					e.printStackTrace();
				}
				
				
			}
		}.start();
	}
    
	private class MyAdapter extends BaseAdapter {

		@Override
		public int getCount() {
			return lists.size();
		}

		@Override
		public Object getItem(int position) {
			return lists.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			View view = null;
			//没有空闲的View可以被使用
			if(convertView == null){
				 view = View.inflate(MainActivity.this, R.layout.item, null);
			}else {
				view = convertView;
			}
			
			//通过View获取要操作的组件
			SmartImageView siv_icon = (SmartImageView) view.findViewById(R.id.iv_icon);
			TextView tv_title = (TextView) view.findViewById(R.id.tv_title);
			TextView tv_content = (TextView) view.findViewById(R.id.tv_content);
			TextView tv_comment = (TextView) view.findViewById(R.id.tv_comment);
			
			NewsItem ni = lists.get(position);
			tv_title.setText(ni.title);
			tv_content.setText(ni.description);
			
			//通过自定义的组件,直接设置Url,进行图片的展示
			siv_icon.setImageUrl(ni.image);
			String type = ni.type;
			if("1".equals(type)){
				tv_comment.setText(ni.comment + "条评论")	;
				tv_comment.setTextColor(Color.BLACK);
			}else if("2".equals(type)){
				tv_comment.setText("专题");
				tv_comment.setTextColor(Color.RED);
			}else if("3".equals(type)){
				tv_comment.setText("独家");
				tv_comment.setTextColor(Color.BLUE);
			}
			return view;
		}
		
	}
}

10.自定义View组件

public class MySmartImageView extends ImageView{
	
	private Handler handler = new Handler(){
		public void handleMessage(Message msg) {
			if(msg.what == GET_PIC_SUCCESS){
				//如果成功显示从网络获取的图片
				setImageBitmap((Bitmap) msg.obj);
			}else if (msg.what == GET_PIC_FAILURE){
				//如果失败显示默认的图片
				setImageResource(R.drawable.ic_launcher);
			}
		}
	};
	private static final int GET_PIC_FAILURE = 0;
	private static final int GET_PIC_SUCCESS = 1;

	//三个参数的构造,当布局文件中组件有style属性时,
	//如style="@style/AppBaseTheme",就会默认调用这个构造函数
	public MySmartImageView(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
	}

	//两个参数的构造,用来解析xml布局文件中的MySmartImageView
	//会将布局文件中的属性,如android:id="@+id/iv_icon"封装为AttributeSet对象
	public MySmartImageView(Context context, AttributeSet attrs) {
		super(context, attrs);
	}

	//一个参数的构造,使得程序员直接可以在代码中创建MySmartImageView对象
	public MySmartImageView(Context context) {
		super(context);
	}

	public void setUrl(final String path){
		new Thread(){
			
			@Override
			public void run() {
				try {
					URL url = new URL(path);
					HttpURLConnection connection = (HttpURLConnection) url.openConnection();
					connection.setRequestMethod("GET");
					connection.setConnectTimeout(10000);
					int code = connection.getResponseCode();
					if(code == 200){
						Bitmap bitmap = BitmapFactory.decodeStream(connection.getInputStream());
						Message message = Message.obtain();
						message.obj = bitmap;
						message.what = GET_PIC_SUCCESS ;
						handler.sendMessage(message);
						
					}else {
						Message message = Message.obtain();
						message.what = GET_PIC_FAILURE;
						handler.sendMessage(message);
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
				
			}
		}.start();
	}
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值