Android not Responding(应用程序无响应) 阻塞了主线程 ANR异常
异常:
CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
只有原始的线程(主线程, ui线程)才能修改view对象.
在子线程中修改view的显示状态, 会报上面异常.
内部类 访问 外部类的 方法的变量时,要将变量用 final 修饰
1. 当宽为0 时或高为0 时,则表示当前控件的权重
2. 当指定了宽或高时,则表示当前控件渲染的优先级,值越大,则表示越低
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" >
<ImageView
android:id="@+id/iv_icon"
android:layout_width="fill_parent"
android:layout_height="0dip"
android:layout_weight="1" />
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<EditText
android:id="@+id/et_url"
android:layout_width="0dip"
android:text="http://imgstatic.baidu.com/img/image/d833c895d143ad4bf450b6dd80025aafa40f06b4_%E5%89%AF%E6%9C%AC.jpg"
android:layout_height="wrap_content"
android:singleLine="true"
android:layout_weight="1" />
<Button
android:id="@+id/btn_submit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Go"
android:textSize="20sp" />
</LinearLayout>
</LinearLayout>
public class MainActivity extends Activity implements OnClickListener {
private static final String TAG = "MainActivity" ;
protected static final int ERROR = 1 ;
private final int SUCCESS = 0 ;
private EditText etUrl;
private ImageView ivIcon;
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
super .handleMessage(msg);
Log.i(TAG, "what = " + msg.what);
if (msg.what == SUCCESS) {
ivIcon.setImageBitmap((Bitmap) msg.obj);
} else if (msg.what == ERROR) {
Toast.makeText(MainActivity.this , "抓去失败" , 0 ).show();
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super .onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ivIcon = (ImageView) findViewById(R.id.iv_icon);
etUrl = (EditText) findViewById(R.id.et_url);
findViewById(R.id.btn_submit).setOnClickListener(this );
}
@Override
public void onClick(View v) {
final String url = etUrl.getText().toString();
new Thread(new Runnable() {
@Override
public void run() {
Bitmap bitmap = getImageFromNet(url);
if (bitmap != null ) {
Message msg = new Message();
msg.what = SUCCESS;
msg.obj = bitmap;
handler.sendMessage(msg);
} else {
Message msg = new Message();
msg.what = ERROR;
handler.sendMessage(msg);
}
}}).start();
}
private Bitmap getImageFromNet(String url) {
HttpURLConnection conn = null ;
try {
URL mURL = new URL(url);
conn = (HttpURLConnection) mURL.openConnection();
conn.setRequestMethod("GET" );
conn.setConnectTimeout(10000 );
conn.setReadTimeout(5000 );
int responseCode = conn.getResponseCode();
if (responseCode == 200 ) {
InputStream is = conn.getInputStream();
Bitmap bitmap = BitmapFactory.decodeStream(is);
return bitmap;
} else {
Log.i(TAG, "访问失败: responseCode = " + responseCode);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (conn != null ) {
conn.disconnect();
}
}
return null ;
}
}
public class MainActivity extends Activity {
private static final String TAG = "MainActivity" ;
private static final int SUCCESS = 0 ;
protected static final int ERROR = 1 ;
private EditText etUrl;
private TextView tvHtml;
private Handler handler = new Handler() {
@Override
public void handleMessage (Message msg) {
super .handleMessage(msg);
switch (msg.what) {
case SUCCESS:
tvHtml.setText((String) msg.obj);
break ;
case ERROR:
Toast.makeText(MainActivity.this , "访问失败" , 0 ).show();
break ;
default :
break ;
}
}
};
@Override
protected void onCreate (Bundle savedInstanceState) {
super .onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
etUrl = (EditText) findViewById(R.id.et_url);
tvHtml = (TextView) findViewById(R.id.tv_html);
}
public void getHtml (View v) {
final String url = etUrl.getText().toString();
new Thread(new Runnable() {
@Override
public void run () {
String html = getHtmlFromInternet(url);
if (!TextUtils.isEmpty(html)) {
Message msg = new Message();
msg.what = SUCCESS;
msg.obj = html;
handler.sendMessage(msg);
} else {
Message msg = new Message();
msg.what = ERROR;
handler.sendMessage(msg);
}
}
}).start();
}
/**
* 根据给定的url访问网络, 抓去html代码
* @param url
* @return
*/
protected String getHtmlFromInternet (String url) {
try {
URL mURL = new URL(url);
HttpURLConnection conn = (HttpURLConnection) mURL.openConnection();
conn.setRequestMethod("GET" );
conn.setConnectTimeout(10000 );
conn.setReadTimeout(5000 );
int responseCode = conn.getResponseCode();
if (responseCode == 200 ) {
InputStream is = conn.getInputStream();
String html = getStringFromInputStream(is);
return html;
} else {
Log.i(TAG, "访问失败: " + responseCode);
}
} catch (Exception e) {
e.printStackTrace();
}
return null ;
}
/**
* 根据流返回一个字符串信息
* @param is
* @return
* @throws IOException
*/
private String getStringFromInputStream (InputStream is) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte [] buffer = new byte [1024 ];
int len = -1 ;
while ((len = is.read(buffer)) != -1 ) {
baos.write(buffer, 0 , len);
}
is.close();
String html = baos.toString();
String charset = "utf-8" ;
if (html.contains("gbk" ) || html.contains("gb2312" )
|| html.contains("GBK" ) || html.contains("GB2312" )) {
charset = "gbk" ;
}
html = new String(baos.toByteArray(), charset);
baos.close();
return html;
}
}