方法一(1)
继承ContentObserver 写成抽象类
/*
* Copyright (C) 2013 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.settings.accessibility;
import android.content.ContentResolver;
import android.database.ContentObserver;
import android.net.Uri;
import android.os.Handler;
import android.provider.Settings;
abstract class SettingsContentObserver extends ContentObserver {
public SettingsContentObserver(Handler handler) {
super(handler);
}
public void register(ContentResolver contentResolver) {
contentResolver.registerContentObserver(Settings.Secure.getUriFor(
Settings.Secure.ACCESSIBILITY_ENABLED), false, this);
contentResolver.registerContentObserver(Settings.Secure.getUriFor(
Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES), false, this);
}
public void unregister(ContentResolver contentResolver) {
contentResolver.unregisterContentObserver(this);
}
@Override
public abstract void onChange(boolean selfChange, Uri uri);
}
private final Handler mHandler = new Handler();
private final SettingsContentObserver mSettingsContentObserver =
new SettingsContentObserver(mHandler) {
@Override
public void onChange(boolean selfChange, Uri uri) {
loadInstalledServices();
updateServicesPreferences();
}
};
mSettingsContentObserver.register(getContentResolver());
mSettingsContentObserver.unregister(getContentResolver());
适用于不能确定监听的url 的类型及其细节,可扩展性强。
方法(二) 写成类,在需要引用的地方new 一个实例
1、 观察飞行模式状态的ContentObserver派生类,AirplaneContentObserver.javapackage com.qin.contentobserver;
import android.content.Context;
import android.database.ContentObserver;
import android.net.Uri;
import android.os.Handler;
import android.provider.*;
import android.provider.Settings.SettingNotFoundException;
import android.util.Log;
//用来观察system表里飞行模式所在行是否发生变化 , “行”内容观察者
public class AirplaneContentObserver extends ContentObserver {
private static String TAG = "AirplaneContentObserver" ;
private static int MSG_AIRPLANE = 1 ;
private Context mContext;
private Handler mHandler ; //此Handler用来更新UI线程
public AirplaneContentObserver(Context context, Handler handler) {
super(handler);
mContext = context;
mHandler = handler ;
}
/**
* 当所监听的Uri发生改变时,就会回调此方法
*
* @param selfChange 此值意义不大 一般情况下该回调值false
*/
@Override
public void onChange(boolean selfChange) {
Log.i(TAG, "-------------the airplane mode has changed-------------");
// 系统是否处于飞行模式下
try {
int isAirplaneOpen = Settings.System.getInt(mContext.getContentResolver(), Settings.System.AIRPLANE_MODE_ON);
Log.i(TAG, " isAirplaneOpen -----> " +isAirplaneOpen) ;
mHandler.obtainMessage(MSG_AIRPLANE,isAirplaneOpen).sendToTarget() ;
}
catch (SettingNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} 2、观察系统里短消息的数据库变化的ContentObserver派生类,SMSContentObserver.javapackage com.qin.contentobserver;
import android.content.Context;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Handler;
import android.util.Log;
//用来观察系统里短消息的数据库变化 ”表“内容观察者,只要信息数据库发生变化,都会触发该ContentObserver 派生类
public class SMSContentObserver extends ContentObserver {
private static String TAG = "SMSContentObserver";
private int MSG_OUTBOXCONTENT = 2 ;
private Context mContext ;
private Handler mHandler ; //更新UI线程
public SMSContentObserver(Context context,Handler handler) {
super(handler);
mContext = context ;
mHandler = handler ;
}
/**
* 当所监听的Uri发生改变时,就会回调此方法
*
* @param selfChange 此值意义不大 一般情况下该回调值false
*/
@Override
public void onChange(boolean selfChange){
Log.i(TAG, "the sms table has changed");
//查询发件箱里的内容
Uri outSMSUri = Uri.parse("content://sms/sent") ;
Cursor c = mContext.getContentResolver().query(outSMSUri, null, null, null,"date desc");
if(c != null){
Log.i(TAG, "the number of send is"+c.getCount()) ;
StringBuilder sb = new StringBuilder() ;
//循环遍历
while(c.moveToNext()){
// sb.append("发件人手机号码: "+c.getInt(c.getColumnIndex("address")))
// .append("信息内容: "+c.getInt(c.getColumnIndex("body")))
// .append("是否查看: "+c.getInt(c.getColumnIndex("read")))
// .append("发送时间: "+c.getInt(c.getColumnIndex("date")))
// .append("\n");
sb.append("发件人手机号码: "+c.getInt(c.getColumnIndex("address")))
.append("信息内容: "+c.getString(c.getColumnIndex("body")))
.append("\n");
}
c.close();
mHandler.obtainMessage(MSG_OUTBOXCONTENT, sb.toString()).sendToTarget();
}
}
} 3、主工程逻辑为MainActivity.java,对短消息的观察Uri,通过测试我发现只能监听此Uri “content://sms” (等同于"content://sms/"),而不能监听其他的Uri,比如"content://sms/outbox"等。package com.qin.contentobserver;
import android.app.Activity;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.*;
import android.util.Log;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
private TextView tvAirplane;
private EditText etSmsoutbox;
// Message 类型值
private static final int MSG_AIRPLANE = 1;
private static final int MSG_OUTBOXCONTENT = 2;
private AirplaneContentObserver airplaneCO;
private SMSContentObserver smsContentObserver;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tvAirplane = (TextView) findViewById(R.id.tvAirplane);
etSmsoutbox = (EditText) findViewById(R.id.smsoutboxContent);
// 创建两个对象
airplaneCO = new AirplaneContentObserver(this, mHandler);
smsContentObserver = new SMSContentObserver(this, mHandler);
//注册内容观察者
registerContentObservers() ;
}
private void registerContentObservers() {
// 通过调用getUriFor 方法获得 system表里的"飞行模式"所在行的Uri
Uri airplaneUri = Settings.System.getUriFor(Settings.System.AIRPLANE_MODE_ON);
// 注册内容观察者
getContentResolver().registerContentObserver(airplaneUri, false, airplaneCO);
// ”表“内容观察者 ,通过测试我发现只能监听此Uri -----> content://sms
// 监听不到其他的Uri 比如说 content://sms/outbox
Uri smsUri = Uri.parse("content://sms");
getContentResolver().registerContentObserver(smsUri, true,smsContentObserver);
}
private Handler mHandler = new Handler() {
public void handleMessage(Message msg) {
System.out.println("---mHanlder----");
switch (msg.what) {
case MSG_AIRPLANE:
int isAirplaneOpen = (Integer) msg.obj;
if (isAirplaneOpen != 0)
tvAirplane.setText("飞行模式已打开");
else if (isAirplaneOpen == 0)
tvAirplane.setText("飞行模式已关闭");
break;
case MSG_OUTBOXCONTENT:
String outbox = (String) msg.obj;
etSmsoutbox.setText(outbox);
break;
default:
break;
}
}
};
} 在此基础上,你可以利用ContentObserver去实现短信黑名单以及悄悄发送短信等技巧,具体可以参考这篇博客: < 接受指定号码的短信>
总结: 使用ContentObserver的情况主要有一下两者情况: 1、需要频繁检测的数据库或者某个数据是否发生改变,如果使用线程去操作,很不经济而且很耗时 ; 2、在用户不知晓的情况下对数据库做一些事件,比如:悄悄发送信息、拒绝接受短信黑名单等;
在这两种情形下,使用ContentObserver无疑是最好的利刃了。
这样适用于具体的url 监听,数据变动之后动态的通知页面的调整和相应的动作。
http://bbs.apkbus.com/article/3529