无废话Android之内容观察者ContentObserver、获取和保存系统的联系人信息、网络图片查看器、网络html查看器、使用异步框架Android-Async-Http(4)

2022-11-01,,,,

1.内容观察者ContentObserver
如果ContentProvider的访问者需要知道ContentProvider中的数据发生了变化,可以在ContentProvider 发生数据变化时调用getContentResolver().notifyChange(uri, null)来通知注册在此URI上的访问者,例子如下:
private static final Uri URI = Uri.parse("content://person.db");
public class PersonContentProvider extends ContentProvider {
public Uri insert(Uri uri, ContentValues values) {
db.insert("person", "personid", values);
getContext().getContentResolver().notifyChange(uri, null);
}
}
如果ContentProvider的访问者需要得到数据变化通知,必须使用ContentObserver对数据(数据采用uri描述)进行监听,当监听到数据变化通知时,系统就会调用ContentObserver的onChange()方法:
getContentResolver().registerContentObserver(Uri.parse("content://person.db"),
true, new PersonObserver(new Handler()));
public class PersonObserver extends ContentObserver{
public PersonObserver(Handler handler) {
super(handler);
}
public void onChange(boolean selfChange) {
//此处可以进行相应的业务处理
Toast.makeText(MainActivity.this, "数据库内容发送变化了!", 0).show();
}
} .获取系统的联系人信息
public void getContacts(View view) {
ContentResolver resolver = this.getContentResolver();
Uri uri = Uri.parse("content://com.android.contacts/raw_contacts");
Uri dataUri = Uri.parse("content://com.android.contacts/data");
Cursor cursor = resolver.query(uri, null, null, null, null);
if (cursor.moveToLast()) {
String id = cursor.getString(cursor.getColumnIndex("contact_id"));
if (id != null) {
Cursor dataCursor = resolver.query(dataUri, null,"raw_contact_id=?", new String[] { id }, null);
while (dataCursor.moveToNext()) {
String data1 = dataCursor.getString(dataCursor.getColumnIndex("data1"));
String mimetype = dataCursor.getString(dataCursor.getColumnIndex("mimetype"));
Toast.makeText(this, data1 + " = " + mimetype, 0).show();
}
dataCursor.close();
} else {
Toast.makeText(this, "空!", 0).show();
}
} cursor.close();
} <uses-permission android:name="android.permission.READ_CONTACTS" /> .保存联系人到系统通讯录
public void writeContact(View view) {
ContentResolver resolver = this.getContentResolver();
Uri uri = Uri.parse("content://com.android.contacts/raw_contacts");
Uri dataUri = Uri.parse("content://com.android.contacts/data");
Cursor cursor = resolver.query(uri, new String[] { "_id" }, null, null,
null);
if (cursor.moveToLast()) {
int lastId = cursor.getInt(0);
int newId = lastId + 1;
ContentValues values = new ContentValues();
values.put("contact_id", newId);
resolver.insert(uri, values); ContentValues phoneValues = new ContentValues();
phoneValues.put("data1", "13500001111");
phoneValues.put("mimetype", "vnd.android.cursor.item/phone_v2");
phoneValues.put("raw_contact_id", newId);
resolver.insert(dataUri, phoneValues); ContentValues emaiValues = new ContentValues();
emaiValues.put("data1", "reality_jie@qq.com");
emaiValues.put("mimetype", "vnd.android.cursor.item/email_v2");
emaiValues.put("raw_contact_id", newId);
resolver.insert(dataUri, emaiValues);
ContentValues nameValues = new ContentValues();
nameValues.put("data1", "weijie");
nameValues.put("mimetype", "vnd.android.cursor.item/name");
nameValues.put("raw_contact_id", newId);
resolver.insert(dataUri, nameValues);
}
cursor.close();
Toast.makeText(this, "保存成功", 0).show(); } <uses-permission android:name="android.permission.WRITE_CONTACTS" /> .网络图片查看器
public class MainActivity extends Activity { protected static final int UPDATE_UI = 1;
protected static final int ERROR = 2;
private ImageView iv_beauty;
private EditText et_path; // 主线程创建消息处理器
Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
if (msg.what == UPDATE_UI) {
iv_beauty.setImageBitmap((Bitmap) msg.obj);
} else {
Toast.makeText(getApplicationContext(), "图片获取失败!", 0)
.show();
}
}
}; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.iv_beauty = (ImageView) this.findViewById(R.id.iv_beauty);
this.et_path = (EditText) this.findViewById(R.id.et_path);
} public void watch(View view) {
final String path = this.et_path.getText().toString().trim();
if (TextUtils.isEmpty(path)) {
Toast.makeText(this, "路径不能为空", 0).show();
} else {
new Thread() {
@Override
public void run() {
try {
URL url = new URL(path);
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
// 设置请求方式
connection.setRequestMethod("GET");
// 设置超时时间
connection.setConnectTimeout(10000); // connection.setRequestProperty(field, newValue) int code = connection.getResponseCode();
if (code == 200) {
InputStream is = connection.getInputStream();
Bitmap bitmap = BitmapFactory.decodeStream(is); // 告诉主线程一个消息,帮我更新ui,内容:bitmap
Message msg = new Message();
msg.what = UPDATE_UI;
msg.obj = bitmap;
handler.sendMessage(msg);
} else {
Message msg = new Message();
msg.what = ERROR;
handler.sendMessage(msg);
}
} catch (Exception e) {
e.printStackTrace();
Message msg = new Message();
msg.what = ERROR;
handler.sendMessage(msg);
}
} }.start(); }
}
} .网络html查看器
<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" > <EditText
android:id="@+id/et_path"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="请输入网址" /> <Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="确定"
android:onClick="click" /> <ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent" > <TextView
android:id="@+id/tv_content"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</ScrollView> </LinearLayout> public class MainActivity extends Activity { protected static final int ERROR = 0;
protected static final int SHOW_CONTENT = 1;
private EditText et_path;
private TextView tv_content; private Handler handler = new Handler() {
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case ERROR:
Toast.makeText(MainActivity.this, "获取网页信息失败",
Toast.LENGTH_SHORT).show();
break;
case SHOW_CONTENT:
tv_content.setText((String) msg.obj);
break;
} }; }; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.et_path = (EditText) this.findViewById(R.id.et_path);
this.tv_content = (TextView) this.findViewById(R.id.tv_content);
} public void click(View view) {
final String path = this.et_path.getText().toString().trim();
if (TextUtils.isEmpty(path)) {
Toast.makeText(this, "路径不能为空!", Toast.LENGTH_SHORT).show();
} else {
new Thread() { public void run() {
try {
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url
.openConnection();
conn.setRequestMethod("GET");
conn.setReadTimeout(5000);
int code = conn.getResponseCode();
if (code == 200) {
InputStream is = conn.getInputStream();
String result = StreamTool.readInputStream(is);
Message msg = new Message();
msg.what = SHOW_CONTENT;
msg.obj = result;
handler.sendMessage(msg);
} else {
Message msg = new Message();
msg.what = ERROR;
handler.sendMessage(msg);
}
} catch (Exception e) {
e.printStackTrace();
Message msg = new Message();
msg.what = ERROR;
handler.sendMessage(msg);
}
}; }.start();
}
} } public class StreamTool { public static String readInputStream(InputStream is) {
try { ByteArrayOutputStream out = new ByteArrayOutputStream();
int length = 0;
byte[] buffer = new byte[];
if ((length = is.read(buffer)) != -1) {
out.write(buffer, 0, length);
}
byte[] result = out.toByteArray();
String temp = new String(result);//默认utf-8
if(temp.contains("gb2312")){
return new String(result,"gb2312");
}
return temp;
} catch (Exception e) {
// TODO: handle exception
}
return "转换失败";
} } <uses-permission android:name="android.permission.INTERNET"/> 6.使用异步框架Android-Async-Http
1、下载:https://github.com/loopj/android-async-http
2、在工程中加入jar包,或直接把源文件加到工程中
3、android-async-http文档:http://loopj.com/android-async-http/ AsyncHttp使用回调的方法处得请求的结果。 AsyncHttpClient client = new AsyncHttpClient();
client.get("http://www.google.com", new AsyncHttpResponseHandler() {
@Override
public void onSuccess(String response) {
System.out.println(response);
}
}); 最好建一个静态的AsyncHttpClient public class HttpUtil { private static AsyncHttpClient client = new AsyncHttpClient(); // 实例话对象 static { client.setTimeout(10000); // 设置链接超时,如果不设置,默认为10s
} // 用一个完整url获取一个string对象
public static void get(String urlString, AsyncHttpResponseHandler res)
{ client.get(urlString, res); } // url里面带参数
public static void get(String urlString, RequestParams params,
AsyncHttpResponseHandler res){ client.get(urlString, params, res); } // 不带参数,获取json对象或者数组
public static void get(String urlString, JsonHttpResponseHandler res) {
client.get(urlString, res); } // 带参数,获取json对象或者数组
public static void get(String urlString, RequestParams params,
JsonHttpResponseHandler res) { client.get(urlString, params, res); } // 下载数据使用,会返回byte数据
public static void get(String uString, BinaryHttpResponseHandler bHandler) { client.get(uString, bHandler); } public static AsyncHttpClient getClient(){ return client;
} } 下载: public void downloadClick(View view) {
String url = "http://f.hiphotos.baidu.com/album/w%3D2048/sign=38c43ff7902397ddd6799f046dbab3b7/9c16fdfaaf51f3dee973bf7495eef01f3b2979d8.jpg";
HttpUtil.get(url, new BinaryHttpResponseHandler() {
@Override
public void onSuccess(byte[] arg0) {
super.onSuccess(arg0);
File file = Environment.getExternalStorageDirectory();
File file2 = new File(file, "cat");
file2.mkdir();
file2 = new File(file2, "cat.jpg");
try {
FileOutputStream oStream = new FileOutputStream(file2);
oStream.write(arg0);
oStream.flush();
oStream.close();
textView.setText("可爱的猫咪已经保存在sdcard里面");
} catch (Exception e) {
e.printStackTrace();
Log.i("hck", e.toString());
}
}
});
} 上传:
public void uploadClick(View view){
String path="http://10.0.2.2:8080/jsontest/servlet/UploadServlet";
File myFile = new File("/sdcard/cat/cat.jpg");
RequestParams params = new RequestParams();
try {
params.put("filename", myFile); AsyncHttpClient client = new AsyncHttpClient();
client.post(path, params, new AsyncHttpResponseHandler(){ @Override
public void onSuccess(int statusCode, String content) {
// TODO Auto-generated method stub
super.onSuccess(statusCode, content);
Toast.makeText(MainActivity.this, "上传成功!", Toast.LENGTH_LONG).show();
} }); } catch(FileNotFoundException e) { }
}

废话Android之内容观察者ContentObserver、获取和保存系统的联系人信息、网络图片查看器、网络html查看器、使用异步框架Android-Async-Http(4)的相关教程结束。

《无废话Android之内容观察者ContentObserver、获取和保存系统的联系人信息、网络图片查看器、网络html查看器、使用异步框架Android-Async-Http(4).doc》

下载本文的Word格式文档,以方便收藏与打印。