Android(九)

一、互联网连接(需要联网)
  1. 代码
    	Button btn=(Button) findViewById(R.id.button1);
            btn.setOnClickListener(new OnClickListener(  ) {
    			public void onClick(View arg0) {
    				new AsyncTask<String, Void, Void>(){//异步任务,在后台执行
    					protected Void doInBackground(String... arg0) {
    						// 准备一个url对象
    						try {
    							URL url=new URL(arg0[0]);
    							//获取互联网连接
    							URLConnection connection=url.openConnection();
    							//获取服务器返回的数据
    							InputStream is=connection.getInputStream();
    							//打开数据
    							InputStreamReader isr=new InputStreamReader(is,"utf-8");
    							//读取数据
    							BufferedReader br=new BufferedReader(isr);
    							String line;//按行读
    							//当读的行不为空,就一直读,直到结束
    							while((line=br.readLine())!=null){
    								System.out.println(line);
    							}
    							br.close();
    							isr.close();
    							is.close();
    						} catch (MalformedURLException e) {
    							e.printStackTrace();
    						} catch (IOException e) {
    							// TODO Auto-generated catch block
    							e.printStackTrace();
    						}
    						return null;
    					}
    					
    				}.execute("https://www.baidu.com");
    			}
    		});  
    
  2. 配置权限
    	 <uses-permission android:name="android.permission.INTERNET"/>
    
二、根据图片地址在app内加载一张图片
  1. 获取图片资源
    	public class GetHtmlData {
    	//1.获取图片资源方法
    	public static byte[] getImage(String path) throws Exception{
    		URL url=new URL(path);
    		HttpURLConnection connection=(HttpURLConnection) url.openConnection();
    		//设置一个访问超时时间
    		connection.setConnectTimeout(6000);//单位为毫秒,这里设为6秒
    		//设置请求类型
    		connection.setRequestMethod("GET");
    		//判断访问网络的状态码
    		if(connection.getResponseCode()!=200){
    			throw new RuntimeException("请求失败");
    		}
    		//获取内容
    		InputStream is=connection.getInputStream();
    		//使用专门解析字节码的函数
    		byte [] bt=StreamTool.read(is);
    		is.close();
    		return bt;
    	}
    	public static String getHtml(String path) throws Exception{
    		//2.获得网页的方法
    		URL url=new URL(path);
    		HttpURLConnection connection=(HttpURLConnection) url.openConnection();
    		//设置一个访问超时时间
    		connection.setConnectTimeout(6000);//单位为毫秒,这里设为6秒
    		//设置请求类型
    		connection.setRequestMethod("GET");
    		//判断访问网络的状态码
    		if(connection.getResponseCode()==200){//成功访问后,要干的内容
    			InputStream is=connection.getInputStream();
    			byte [] data=StreamTool.read(is);
    			String html=new String(data,"utf-8");
    			return html;
    		}
    		return null;
    	}
    }
    
  2. 设置解析数据流的工具
    	public class StreamTool {//用来解析数据流的工具
    	public static byte[] read(InputStream inputStream) throws Exception{
    		ByteArrayOutputStream outputStream=new ByteArrayOutputStream();
    		byte[] buffer=new byte[1024];
    		int len=0;
    		while((len=inputStream.read(buffer))!=-1){
    			outputStream.write(buffer,0,len);
    		}
    		inputStream.close();	
    		return outputStream.toByteArray();
    	}	
    }
    
  3. 设置权限
    	<uses-permission android:name="android.permission.INTERNET"/>
    
  4. 设置布局界面并获取图片
    	public class MainActivity extends Activity {	
    	private TextView textMenu;
    	private TextView textShow;
    	private ScrollView scroll;
    	private ImageView imgpic;
    	private Bitmap bitmap;
    	private WebView webView;
    	private String Image_Url="https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1564466297038&di=ec5942c876dfe1f366608b01746cfa91&imgtype=0&src=http%3A%2F%2Fwx2.sinaimg.cn%2Flarge%2F006agyVmly1g5ftv14rwlj30u01bogzi.jpg";
        private String detail="";
        private String Html_Url="https://www.baidu.com";
    	@Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            textShow=(TextView) findViewById(R.id.textShow);
            textMenu=(TextView)findViewById(R.id.textMenu);
            imgpic=(ImageView)findViewById(R.id.imgpic);
            scroll=(ScrollView)findViewById(R.id.scroll);
            webView=(WebView) findViewById(R.id.webView1);
            registerForContextMenu(textMenu);
        }
        @Override
        public void onCreateContextMenu(ContextMenu menu, View v,
        		ContextMenuInfo menuInfo) {
        	MenuInflater inflater=new MenuInflater(this);
        	inflater.inflate(R.menu.menus, menu);
        	super.onCreateContextMenu(menu, v, menuInfo);
        }
        //选择上下文菜单后执行的东西
        @Override
        public boolean onContextItemSelected(MenuItem item) {
        	switch (item.getItemId()) {
    		case R.id.one:
    			//从网络中加载图片,显示到自己的界面
    			
    			new Thread(){//开启新线程
    				public void run(){
    					try{
    						byte[] data=GetHtmlData.getImage(Image_Url);
    						bitmap=BitmapFactory.decodeByteArray(data,0, data.length);
    					}catch(Exception e){
    						e.printStackTrace();
    					}
    					//System.out.println("1111111111111111111111"+bitmap);
    					handler.sendEmptyMessage(0x001);
    					/*hideAll();
    					imgpic.setVisibility(View.VISIBLE);
    					imgpic.setImageBitmap(bitmap);*/
    				}
    			}.start();
    			break;
    		case R.id.two://获取网络地址的html代码
    			new Thread(){
    				public void run(){
    					try {
    						detail=GetHtmlData.getHtml(Html_Url);
    					} catch (Exception e) {
    						// TODO Auto-generated catch block
    						e.printStackTrace();
    					}
    					//告诉主程序处理这里
    					handler.sendEmptyMessage(0x002);//这里是可以随便写一个特征,如0x002
    				}
    			}.start();
    			break;
    		case R.id.three://根据已经获取的html来获取网页
    			if(detail.equals("")){
    				Toast.makeText(getApplicationContext(), "先获取网页在说", 1).show();
    			}else{
    				handler.sendEmptyMessage(0x003);
    			}
    			break;
    		default:
    			break;
    		}
        	return super.onContextItemSelected(item);
        }
        //隐藏所有层次
        private void hideAll(){
        	imgpic.setVisibility(View.GONE);
        	scroll.setVisibility(View.GONE);
        	webView.setVisibility(View.GONE);
        }
        //写个函数用来刷新界面来显示相关的东西
        private Handler handler=new Handler(){
        	public void handleMessage(android.os.Message msg){
        		switch (msg.what) {
    			case 0x001:
    				hideAll();
    				imgpic.setVisibility(View.VISIBLE);
    				imgpic.setImageBitmap(bitmap);
    				break;
    			case 0x002:
    				hideAll();
    				scroll.setVisibility(View.VISIBLE);//显示
    				textShow.setText(detail);
    				Toast.makeText(getApplicationContext(), "已获取网页", 1).show();
    				break;
    			case 0x003:
    				hideAll();
    				webView.setVisibility(View.VISIBLE);
    				webView.loadDataWithBaseURL("", detail, "text/html", "utf-8", "");
    				Toast.makeText(getApplicationContext(), "网页已加载完毕", 1).show();
    				break;
    			default:
    				break;
    			}	
        	}
        };
    }
    
发布了72 篇原创文章 · 获赞 3 · 访问量 3541

猜你喜欢

转载自blog.csdn.net/id__39/article/details/105196572
今日推荐