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) {
String path = et_url.getText().toString();
System.out.println(path);
try {
URL url = new URL(path);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(10000);
int code = connection.getResponseCode();
if(code == 200){
InputStream inputStream = connection.getInputStream();
String result = Utils.getStringFromStream(inputStream);
tv_code.setText(result);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
public class Utils {
public static String getStringFromStream(InputStream inputStream) {
ByteArrayOutputStream baos = new 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) {
e.printStackTrace();
return null;
} finally {
try {
inputStream.close();
baos.close();
} catch (IOException e) {
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;
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() {
String path = et_url.getText().toString();
System.out.println(path);
try {
URL url = new URL(path);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(10000);
int code = connection.getResponseCode();
if(code == 200){
InputStream inputStream = connection.getInputStream();
String result = Utils.getStringFromStream(inputStream);
Message message = Message.obtain();
message.obj = result;
handler.sendMessage(message);
}
} catch (Exception e) {
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(){
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.sendEmptyMessageDelayed(1, 1000);
}
public void count(){
count--;
tv_num.setText(count + "");
handler.sendEmptyMessageDelayed(1, 1000);
}
}
8.runOnUiThread
runOnUiThread(new Runnable() {
@Override
public void 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) {
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);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(10000);
int responseCode = connection.getResponseCode();
if(responseCode == 200){
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();
}
}
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;
if(convertView == null){
view = View.inflate(MainActivity.this, R.layout.item, null);
}else {
view = convertView;
}
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);
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;
public MySmartImageView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public MySmartImageView(Context context, AttributeSet attrs) {
super(context, attrs);
}
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();
}
}