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)的更多相关文章

  1. android API版本对应的系统版本及Android获取手机和系统版本等信息的代码

    学了这么久的Android,竟然一直对其API对应的名称关系一值搞不清楚,现在网上认真看了下资料,转载一个觉得写得不错的作者的文章,记下来: [背景] 之前折腾android期间,慢慢地知道了,And ...

  2. Android中内容观察者的使用---- ContentObserver类详解 (转)

    前言: 工作中,需要开启一个线程大量的查询某个数据库值发送了变化,导致的开销很大,后来在老大的指点下,利用了 ContentObserver完美的解决了该问题,感到很兴奋,做完之后自己也对Conten ...

  3. 内容观察者 ContentObserver 监听短信、通话记录数据库 挂断来电

    Activity public class MainActivity extends ListActivity {     private TextView tv_info;     private  ...

  4. Android 利用内容观察者实现短信窃听

    <Android 内容观察者的原理>中介绍了内容观察者的一些基本原理,并做了简单的实战,本文接着进一步做一个小项目实战 package com.wuyudong.smslistener; ...

  5. [android] 获取系统的联系人信息

    内容提供是实质上是个接口,后门,他给别人提供数据,系统联系人是个比较复杂的内容通过者. 找到/data/data/com.android.providers.contacts/contacts2.db ...

  6. Android获取手机和系统版本等信息的代码

    有时候需要统计手机的型号和版本号,利用程序可以获取到相应的手机信息,对比两部手机发现,厂商不同,某个信息显示方式也不尽相同,具体见: String phoneInfo = "Product: ...

  7. Android_(控件)使用ListView显示Android系统中联系人信息

    使用ListView显示手机中联系人的姓名和电话号码 父类布局activity_main.xml,子类布局line.xml(一个文件的单独存放) 运行截图: (避免泄露信息对部分地方进行了涂鸦O(∩_ ...

  8. Android中内容观察者的使用---- ContentObserver类详解

    详解:http://blog.csdn.net/qinjuning/article/details/7047607

  9. Android 之内容提供者 内容解析者 内容观察者

    contentProvider:ContentProvider在Android中的作用是对外提供数据,除了可以为所在应用提供数据外,还可以共享数据给其他应用,这是Android中解决应用之间数据共享的 ...

随机推荐

  1. 二、 显示加载数据过程的JS

  2. mysql的安装以及基本操作

    一.在Linux 下安装MySQL ubuntu 下可以直接使用apt-get . centos 下yum源有没有就不知道了. 1. sudo apt-get install mysql-server ...

  3. HDU——PKU题目分类

    HDU 模拟题, 枚举1002 1004 1013 1015 1017 1020 1022 1029 1031 1033 1034 1035 1036 1037 1039 1042 1047 1048 ...

  4. phpcms 无法显示缩略图 Call to undefined function image_type_to_extension

    问题背景: 线下的phpcms项目没问题,线上的phpcms新添加的图片缩略图显示有问题,查看了一下php版本,线下是5.5的,线上的是5.1的 问题原因: 看了一下线上的错误日志,显示: PHP F ...

  5. JustMock Lite (Free Mocking Framework For .net)

    通过 Nuget 安装 2.   官网下载(官网不行点这里) 3.   帮助文档 商业版和免费版区别概览 MockingContainer 测试类准备:一般来说也是业务类 public class C ...

  6. ASP.NET 页生命周期概述

    ASP.NET 页生命周期概述 Visual Studio 2005    ASP.NET 页运行时,此页将经历一个生命周期,在生命周期中将执行一系列处理步骤.这些步骤包括初始化.实例化控件.还原和维 ...

  7. ios swift generator 文章推荐

    https://medium.com/swift-programming/sequence-beyond-primitive-iterations-in-swift-80bc2507d8cc /// ...

  8. selenium WebDriver 操作高德地图

    String URL="http://www.amap.com/"; WebDriver driver = new FirefoxDriver(profile); driver.g ...

  9. VS2013,asp.net网站转换为web应用程序

    此功能已经不在右键菜单里了,而在主菜单中的“项目-->转换为WEB应用程序”

  10. git remote 相关用法

    为了便于管理,Git要求每个远程主机都必须指定一个主机名.git remote  命令就用于管理主机名. 不带选项的时候,git remote命令列出所有远程主机. $ git remote orig ...