安卓基础学习5

 1 读取系统联系人

   raw_contact 唯一标示 _id
   data  联系人的数据  
   mimetypes  数据的类型  

 2 向系统插入联系人信息

package com.itcast.contacts;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;

public class MainActivity extends Activity {

	private static final String TAG = "MainActivity";
	private ContentResolver resolver;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		resolver = getContentResolver();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}

	public void readContact(View v) {
		// matcher.addURI(ContactsContract.AUTHORITY, "raw_contacts",
		// RAW_CONTACTS);
		// matcher.addURI(ContactsContract.AUTHORITY, "raw_contacts/#",
		// RAW_CONTACTS_ID);
		// matcher.addURI(ContactsContract.AUTHORITY, "raw_contacts/#/data",
		// RAW_CONTACTS_DATA);
		Uri uri = Uri.parse("content://com.android.contacts/raw_contacts");
		Cursor c = resolver
				.query(uri, new String[] { "_id" }, null, null, null);
		while (c.moveToNext()) {
			String _id = c.getString(0);
			uri = Uri.parse("content://com.android.contacts/raw_contacts/" + _id + "/data");
			Cursor cursor = resolver.query(uri, new String[] { "data1",
					"mimetype" }, null, null, null);
			String name = null;
			String phone = null;
			String email = null;
			while (cursor.moveToNext()) {
				String data = cursor.getString(0);
				String mimetype = cursor.getString(1);
				if ("vnd.android.cursor.item/name".equals(mimetype)) {
					name = data;
				} else if ("vnd.android.cursor.item/phone_v2".equals(mimetype)) {
					phone = data;
				} else if ("vnd.android.cursor.item/email_v2".equals(mimetype)) {
					email = data;
				}
			}
			Log.i(TAG, "name:" + name + ",phone:" + phone + ",email:" + email);
		}

	}

	public void addContact(View v) {
		Uri uri = Uri.parse("content://com.android.contacts/raw_contacts");
		ContentValues values = new ContentValues();
		Uri retUri = resolver.insert(uri, values );
		//获取返回的id
		long raw_contact_id = ContentUris.parseId(retUri);
		
		uri = uri.parse("content://com.android.contacts/data");
		values.clear();
		values.put("raw_contact_id", raw_contact_id);
		values.put("data1", "小国国");
		values.put("mimetype","vnd.android.cursor.item/name");
		resolver.insert(uri, values);

		values.clear();
		values.put("raw_contact_id", raw_contact_id);
		values.put("data1", "123456");
		values.put("mimetype","vnd.android.cursor.item/phone_v2");
		resolver.insert(uri, values);
		

		values.clear();
		values.put("raw_contact_id", raw_contact_id);
		values.put("data1", "[email protected]");
		values.put("mimetype","vnd.android.cursor.item/email_v2");
		resolver.insert(uri, values);
		
	}
}

 3 内容观察者
 4 内容观察者的原理

 5 通过内容观察者检测短信的到来

原理:1.

1.内容观察者注册监听

package com.itcast.provider.query;

import android.app.Activity;
import android.content.ContentResolver;
import android.database.ContentObserver;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Menu;
import android.view.View;

public class MainActivity extends Activity {

	private Uri uri;
	private static final String TAG = "MainActivity";
	private ContentResolver resolver;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);


		Log.i(TAG, "注册内容监听");
		resolver = getContentResolver();
		uri = Uri.parse("content://itcast");
		resolver.registerContentObserver(uri, true, new MyContentObserver(new Handler()));
	}

	
	private class MyContentObserver extends ContentObserver{


		public MyContentObserver(Handler handler) {
			super(handler);
		}
		
		@Override
		public void onChange(boolean selfChange) {
			// TODO Auto-generated method stub
			super.onChange(selfChange);
			resolver.query(uri, new String[]{"*"}, null, null, null);
			Log.i(TAG, "读取到变化。。。");
			
		}
	}
	



}


2.内容提供者中数据发生变化的时候调用getContext().getContentResolver().notifyChange(uri, null);通知注册了本uri的内容观察者

package com.itcast.providers;

import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.net.Uri;
import android.util.Log;

public class MyContentProvider extends ContentProvider {
	private static UriMatcher matcher = new UriMatcher(UriMatcher.NO_MATCH);
	static{
		matcher.addURI("itcast", null, 1);
	}
	private static final String TAG = "MainActivity";

	@Override
	public boolean onCreate() {
		Log.i(TAG, "内容提供者初始化");
		return false;
	}

	@Override
	public Cursor query(Uri uri, String[] projection, String selection,
			String[] selectionArgs, String sortOrder) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public String getType(Uri uri) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Uri insert(Uri uri, ContentValues values) {
		getContext().getContentResolver().notifyChange(uri, null);
		return null;
	}

	@Override
	public int delete(Uri uri, String selection, String[] selectionArgs) {
		getContext().getContentResolver().notifyChange(uri, null);
		return 0;
	}

	@Override
	public int update(Uri uri, ContentValues values, String selection,
			String[] selectionArgs) {
		getContext().getContentResolver().notifyChange(uri, null);
		return 0;
	}

}
3.测试数据库变化
package com.itcast.provider.add;

import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.util.Log;
import android.view.Menu;

public class MainActivity extends Activity {

	private static final String TAG = "MainActivity";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		ContentResolver resolver = getContentResolver();
		ContentValues values = new ContentValues();
		Log.i(TAG, "即将插入数据");
		resolver.insert(Uri.parse("content://itcast"), values );
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}

}


 6 网络图片查看器

package com.itcast.netimageview;

import java.io.File;
import java.io.FileOutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

public class MainActivity extends Activity {

	protected static final int UPDATE = 0;
	protected static final int ERROR = 1;
	protected static final String TAG = "MainActivity";

	private Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case UPDATE:
				Uri uri = (Uri) msg.obj;
				iv.setImageURI(uri);
				break;
			case ERROR:
				Toast.makeText(getApplicationContext(), "获取失败", 1).show();
				break;

			default:
				break;
			}
		};
	};

	private ImageView iv;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		iv = (ImageView) findViewById(R.id.iv);

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}

	public void download(View v) {
		new Thread() {
			public void run() {

				try {
					URL url = new URL("http://10.0.2.2/web/a.jpg");
					HttpURLConnection conn = (HttpURLConnection) url
							.openConnection();

					conn.setConnectTimeout(5000);
					conn.setRequestMethod("GET");

					if (conn.getResponseCode() != 200) {
						throw new RuntimeException("请求url失败");
					}
					File file = new File(Environment.getExternalStorageDirectory(), getFileName(url.getPath()));
					if (file.exists()) {
						Uri uri = Uri.fromFile(file);
						Message msg = Message.obtain();
						msg.what = UPDATE;
						msg.obj = uri;
						handler.sendMessage(msg);
						Log.i(TAG, "从缓存加载");
					}else {
						Bitmap bitmap = BitmapFactory.decodeStream(conn.getInputStream());
						//缓存
						bitmap.compress(CompressFormat.JPEG, 100, new FileOutputStream(file));
						Uri uri = Uri.fromFile(file);
						
						Message msg = Message.obtain();
						msg.what = UPDATE;
						msg.obj = uri;
						handler.sendMessage(msg);
						Log.i(TAG, "从网络加载");
						conn = null;
						url =null;
					}
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					Message msg = Message.obtain();
					msg.what = ERROR;

					handler.sendMessage(msg);
				}

			}

		
		}.start();
	}
	private String getFileName(String path) {
		return path.substring(path.lastIndexOf("/")+1);
	}
}


 7 anr产生的原因如何避免anr异常
 8 android下的消息机制( 强调在4.0的是不允许在主线程访问网络)

 9 android下消息机制的实现(查看Looper的源代码)

安卓基础学习5_第1张图片

 10 图片查看器的异步处理

 11 开源项目smartimageview  碉堡了

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		siv = (SmartImageView) findViewById(R.id.siv);
		siv.setImageUrl("http://10.0.2.2/web/a.jpg");
	}


 12 html源码查看器

package com.itcast.nettextview;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Menu;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {

	protected static final int UPDATE = 0;
	protected static final int ERROR = 1;

	private Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case UPDATE:
				String content = (String) msg.obj;
				tv.setText(content);
				break;
			case ERROR:
				Toast.makeText(getApplicationContext(), "获取失败", 1).show();
				break;

			default:
				break;
			}
		};
	};

	private TextView tv;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		tv = (TextView) findViewById(R.id.tv);

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}

	public void download(View v) {
		new Thread() {
			public void run() {

				try {
					URL url = new URL("http://10.0.2.2/web/index.jsp");
					HttpURLConnection conn = (HttpURLConnection) url
							.openConnection();

					conn.setConnectTimeout(5000);
					conn.setRequestMethod("GET");

					if (conn.getResponseCode() != 200) {
						throw new RuntimeException("请求url失败");
					}

					InputStream in = conn.getInputStream();
					ByteArrayOutputStream bos = new ByteArrayOutputStream();
					byte [] buffer = new byte[1024];
					int len = 0;
					while((len=in.read(buffer))!=-1){
						bos.write(buffer,0,len);
					}
					String content = bos.toString();
					
					Message msg = Message.obtain();
					msg.what = UPDATE;
					msg.obj = content;
					handler.sendMessage(msg);
					conn = null;
					url =null;
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					Message msg = Message.obtain();
					msg.what = ERROR;

					handler.sendMessage(msg);
				}

			};
		}.start();
	}
}


 13 采用get的方式提交数据到服务器&中文乱码问题的处理

URLEncoder.encode()

 14 post方式提交数据到服务器&中文乱码问题的处理

 15 HttpClient  下载文件

package com.itcast.httpdownload;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.os.Bundle;
import android.os.Environment;
import android.app.Activity;
import android.view.Menu;
import android.view.View;

public class MainActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}

	public void download(View v) {
		new Thread() {
			public void run() {
				try {
					HttpClient client = new DefaultHttpClient();
					HttpGet request = new HttpGet("http://10.0.2.2/web/a.jpg");
					HttpResponse response = client.execute(request);
					if (response.getStatusLine().getStatusCode()==200) {
						File file = new File(Environment.getExternalStorageDirectory(), "hehe.jpg");
						FileOutputStream fos = new FileOutputStream(file);
						InputStream is = response.getEntity().getContent();
						byte []buffer = new byte[1024];
						int len = 0;
						while ((len = is.read(buffer))!=-1) {
							fos.write(buffer, 0, len);
						}
						fos.close();
						is.close();
					}
					
					
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			};
		}.start();
	}
}



16解析网络json

package com.itcast.nettextview;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONObject;
import org.xmlpull.v1.XmlPullParser;

import android.R.integer;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.util.Xml;
import android.view.Menu;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.itcast.nettextview.domain.Person;

public class MainActivity extends Activity {

	protected static final int UPDATE = 0;
	protected static final int ERROR = 1;
	protected static final String TAG = "MainActivity";

	private Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case UPDATE:
				break;
			case ERROR:
				Toast.makeText(getApplicationContext(), "获取失败", 1).show();
				break;

			default:
				break;
			}
		};
	};

	private TextView tv;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		tv = (TextView) findViewById(R.id.tv);

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}

	public void download(View v) {
		new Thread() {
			public void run() {

				try {
					URL url = new URL("http://10.0.2.2/web/JsonServlet");
					HttpURLConnection conn = (HttpURLConnection) url
							.openConnection();

					conn.setConnectTimeout(5000);
					conn.setRequestMethod("GET");

					if (conn.getResponseCode() != 200) {
						throw new RuntimeException("请求url失败");
					}

					InputStream in = conn.getInputStream();
					
					ByteArrayOutputStream bos = new ByteArrayOutputStream();
					byte [] buffer = new byte[1024];
					int len = 0;
					while((len=in.read(buffer))!=-1){
						bos.write(buffer,0,len);
					}
					String json = bos.toString();

					//[{id:1,name:"张三",age:18},{id:1,name:"张三",age:18}]
					JSONArray jsonArray = new JSONArray(json);
					for (int i = 0; i < jsonArray.length(); i++) {
						JSONObject jsonObject = (JSONObject) jsonArray.get(i);
						Person person = new Person();
						person._id = Integer.parseInt(jsonObject.getString("id"));
						person.name = jsonObject.getString("name");
						person.age = Integer.parseInt(jsonObject.getString("age"));
						Log.i(TAG, person.toString());
					}
					
					Message msg = Message.obtain();
					msg.what = UPDATE;
					handler.sendMessage(msg);
					conn = null;
					url = null;
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					Message msg = Message.obtain();
					msg.what = ERROR;

					handler.sendMessage(msg);
				}

			};
		}.start();
	}
}

17.解析网络xml

package com.itcast.nettextview;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.xmlpull.v1.XmlPullParser;

import android.R.integer;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.util.Xml;
import android.view.Menu;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.itcast.nettextview.domain.Person;

public class MainActivity extends Activity {

	protected static final int UPDATE = 0;
	protected static final int ERROR = 1;
	protected static final String TAG = "MainActivity";

	private Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case UPDATE:
				break;
			case ERROR:
				Toast.makeText(getApplicationContext(), "获取失败", 1).show();
				break;

			default:
				break;
			}
		};
	};

	private TextView tv;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		tv = (TextView) findViewById(R.id.tv);

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}

	public void download(View v) {
		new Thread() {
			public void run() {

				try {
					URL url = new URL("http://10.0.2.2/web/persons.xml");
					HttpURLConnection conn = (HttpURLConnection) url
							.openConnection();

					conn.setConnectTimeout(5000);
					conn.setRequestMethod("GET");

					if (conn.getResponseCode() != 200) {
						throw new RuntimeException("请求url失败");
					}

					InputStream in = conn.getInputStream();
					XmlPullParser parser = Xml.newPullParser();
					parser.setInput(conn.getInputStream(), "UTF-8");

					int eventType = parser.getEventType();
					List<Person> ps = null;
					Person p =null;
					while (eventType != XmlPullParser.END_DOCUMENT) {
						switch (eventType) {
						case XmlPullParser.START_TAG:
							if (parser.getName().equals("persons")) {
								ps = new ArrayList<Person>();
							}else if (parser.getName().equals("person")) {
								p = new Person();
								p._id = Integer.parseInt(parser.getAttributeValue(0));
							} else if (parser.getName().equals("name")) {
								p.name = parser.nextText();
							} else if (parser.getName().equals("age")) {
								p.age = Integer.parseInt(parser.nextText());
							} 
							break;
						case XmlPullParser.END_TAG:
							if (parser.getName().equals("person")) {
								ps.add(p);
								Log.i(TAG, p.toString());
								p=null;
							} 
							break;
						default:
							break;
						}

						eventType = parser.next();
					}

					Message msg = Message.obtain();
					msg.what = UPDATE;
					handler.sendMessage(msg);
					conn = null;
					url = null;
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					Message msg = Message.obtain();
					msg.what = ERROR;

					handler.sendMessage(msg);
				}

			};
		}.start();
	}
}


你可能感兴趣的:(安卓基础学习5)