郑州网站建设出名吗?,郑州网站建设选微锐,重庆网站制作系统,国际贸易官方网站1.我们在Android下#xff0c;实现使用http协议进行网络通信#xff0c;请求网络数据。这里是获取网络上的图片信息#xff0c;让它可以显示在手机上#xff1b; 但是我们这个手机连接网络是很费时间#xff0c;如果我们在主线程#xff08;UI线程#xff09;中写这个网…1.我们在Android下实现使用http协议进行网络通信请求网络数据。这里是获取网络上的图片信息让它可以显示在手机上 但是我们这个手机连接网络是很费时间如果我们在主线程UI线程中写这个网络连接的逻辑这是很容易报一个错误android.os.NetworkOnMainThreadExceptionAndroid4.0之后引入的异常 主线程很重要它负责监听系统的各种事件如果主线程在一段时间内没有响应系统就会这个应用程序无响应就会产生ANR的异常。下面有必要说明一下这个ANR异常 2.ANRs (Application Not Responding)意思是应用没有响应.在如下情况下Android会报出ANR错误•主线程 (事件处理线程/ UI线程) 在5秒内没有响应输入事件.• BroadcastReceiver 没有在10秒内完成返回.通常情况下下面这些做法会导致ANR1.在主线程内进行网络操作2.在主线程内进行一些缓慢的磁盘操作例如执行没有优化过的SQL查询应用应该在5秒或者10秒内响应否则用户会觉得“这个应用很垃圾”“烂”“慢”…等等逻辑应该是1. new出一个新的线程进行数据请求.2. 获取数据后调用handler.sendMessage方法. 3. 在handler的handle()方法中更新UI. 案例 activity_main.xml 1 RelativeLayout xmlns:androidhttp://schemas.android.com/apk/res/android2 xmlns:toolshttp://schemas.android.com/tools3 android:layout_widthmatch_parent4 android:layout_heightmatch_parent5 tools:context.MainActivity 6 7 Button8 android:onClickclick9 android:layout_widthwrap_content
10 android:layout_heightwrap_content
11 android:layout_centerHorizontaltrue
12 android:layout_centerVerticaltrue
13 android:text点我 /
14
15 /RelativeLayout MainActivity.java package com.itheima.anr;import android.app.Activity;
import android.os.Bundle;
import android.view.View;public class MainActivity extends Activity {Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);}public void click(View view){try {System.out.println(Thread.currentThread().getName());Thread.sleep(6000);//当前线程。} catch (InterruptedException e) {e.printStackTrace();}}} 这里的Thread.sleep6000这里的表示Thread线程是Main线程也就是UI主线程我们之前说过了UI主线程在5s不能响应系统就会认为这个应用程序是不响应的。这里6s5s所以会报错ANRs (Application Not Responding) 3.前面说了这么多也就是说了关于在Android下进行网络连接注意事项网络连接是耗时程序代码下面开始实现网络图片浏览器程序 MainActivity.java: package com.itheima.netimageviewer;import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Base64;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;public class MainActivity extends Activity {private EditText et_path;private ImageView iv;Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);et_path (EditText) findViewById(R.id.et_path);iv (ImageView) findViewById(R.id.iv);}/*** 点击查看网络上的图片* * param view*/public void click(View view) {String path et_path.getText().toString().trim();// http://www.baidu.com/aa.pngif (TextUtils.isEmpty(path)) {Toast.makeText(this, 图片路径不能为空, 0).show();return;}//把文件名编码之后缓冲的路径变成file文件File file new File(getCacheDir(), Base64.encodeToString(path.getBytes(), Base64.DEFAULT));if (file.exists() file.length() 0) {System.out.println(图片存在拿缓存);Bitmap bitmap BitmapFactory.decodeFile(file.getAbsolutePath());iv.setImageBitmap(bitmap);} else {System.out.println(图片不存在获取数据生成缓存);// 通过http请求把图片获取下来。try {// 1.声明访问的路径 url 网络资源 http ftp rtspURL url new URL(path);// 2.通过路径得到一个连接 http的连接HttpURLConnection conn (HttpURLConnection) url.openConnection();// 3.判断服务器给我们返回的状态信息。// 200 成功 302 重定向 404资源没找到 5xx 服务器内部错误int code conn.getResponseCode();if (code 200) {//这个流是用来接收图片的InputStream is conn.getInputStream();// png的图片//这个输出流是吧图片写入安卓系统的储存区的FileOutputStream fos new FileOutputStream(file);//读写操作byte[] buffer new byte[1024];int len -1;while ((len is.read(buffer)) ! -1) {fos.write(buffer, 0, len);}is.close();fos.close();//通过图片工厂来获取文件路径 然后变成图片传递给控件Bitmap bitmap BitmapFactory.decodeFile(file.getAbsolutePath());iv.setImageBitmap(bitmap);} else {// 请求失败Toast.makeText(this, 请求失败, 0).show();}} catch (Exception e) {e.printStackTrace();Toast.makeText(this, 发生异常请求失败, 0).show();}}}
} activity_main.xml: LinearLayout xmlns:androidhttp://schemas.android.com/apk/res/androidxmlns:toolshttp://schemas.android.com/toolsandroid:layout_widthmatch_parentandroid:layout_heightmatch_parentandroid:orientationverticaltools:context.MainActivity EditTextandroid:texthttp://www.baidu.com/img/bd_logo1.pngandroid:idid/et_pathandroid:layout_widthmatch_parentandroid:layout_heightwrap_contentandroid:hint请输入网络图片的路径 /Buttonandroid:onClickclickandroid:layout_widthmatch_parentandroid:layout_heightwrap_contentandroid:text查看 /ImageViewandroid:idid/ivandroid:layout_widthwrap_contentandroid:layout_heightwrap_content //LinearLayout AndroidManifest.xml: ?xml version1.0 encodingutf-8?
manifest xmlns:androidhttp://schemas.android.com/apk/res/androidpackagecom.himi.webpicturewatchandroid:versionCode1android:versionName1.0 uses-permission android:nameandroid.permission.INTERNET/uses-permission android:nameandroid.permission.ACCESS_WIFI_STATE/uses-sdkandroid:minSdkVersion15android:targetSdkVersion17 /applicationandroid:allowBackuptrueandroid:icondrawable/ic_launcherandroid:labelstring/app_nameandroid:themestyle/AppTheme activityandroid:name.MainActivityandroid:labelstring/app_name intent-filteraction android:nameandroid.intent.action.MAIN /category android:nameandroid.intent.category.LAUNCHER //intent-filter/activity/application/manifest 转载于:https://www.cnblogs.com/hebao0514/p/4767538.html