day5,代码不全
1、创建内容提供者并在清单文件中设置,对数据库的插入,删除进行观察
<provider
android:name="cn.itcast.mobilesafe.provider.AppLockProvider"
android:authorities="cn.itcast.applockprovider" >
</provider>
public class AppLockProvider extends ContentProvider {
private static UriMatcher matcher = new UriMatcher(UriMatcher.NO_MATCH);
private static int INSERT = 10;
private static int DELETE = 11;
private AppLockDao dao;
private static Uri changeuri=Uri.parse("content://cn.itcast.applockprovider");
// 静态代码块,把匹配规则设置进来
static {
matcher.addURI("cn.itcast.applockprovider", "insert", INSERT);
matcher.addURI("cn.itcast.applockprovider", "delete", DELETE);
}
@Override
public Uri insert(Uri uri, ContentValues values) {
int result = matcher.match(uri);
if (result == INSERT) {
String packname = (String) values.get("packname");
dao.add(packname);
getContext().getContentResolver().notifyChange(changeuri, null);//通知数据发生改变
} else {
throw new IllegalAccessError("uri地址不正确");
}
return null;
}
@Override
public boolean onCreate() {
dao = new AppLockDao(getContext());
return false;
}
@Override
public int delete(Uri uri, String selection, String[] seleteArgs) {
int result = matcher.match(uri);
if (result == DELETE) {
String packname = seleteArgs[0];
dao.delete(packname);
getContext().getContentResolver().notifyChange(changeuri, null);//通知数据发生改变
} else {
throw new IllegalAccessError("uri地址不正确");
}
return 0;
}
@Override
public String getType(Uri uri) {
// TODO Auto-generated method stub
return null;
}
@Override
public Cursor query(Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder) {
// TODO Auto-generated method stub
return null;
}
@Override
public int update(Uri uri, ContentValues values, String selection,
String[] selectionArgs) {
// TODO Auto-generated method stub
return 0;
}
}
2、在Activity中对插入和删除的行为用内容提供者进行操作
if (dao.find(packname)) {
// dao.delete(packname);注释这行替换为下一行
getContentResolver()
.delete(Uri
.parse("content://cn.itcast.applockprovider/delete"),
null, new String[] { packname });
lockappinfos.remove(packname);
iv.setImageResource(R.drawable.unlock);
} else {
// dao.add(packname);// 程序包名保存到数据库中
ContentValues values = new ContentValues();
values.put("packname", packname);
getContentResolver()
.insert(Uri
.parse("content://cn.itcast.applockprovider/insert"),
values);
lockappinfos.add(packname);
iv.setImageResource(R.drawable.lock);
}
3、在服务当中的onCreate()方法中执行
getContentResolver().registerContentObserver(Uri.parse("content://cn.itcast.applockprovider"), true, new MyObserver(new Handler()));
4、新建MyObserver,更新数据库内容
private class MyObserver extends ContentObserver{
public MyObserver(Handler handler) {
super(handler);
// TODO Auto-generated constructor stub
}
@Override
public void onChange(boolean selfChange) {
// TODO Auto-generated method stub
super.onChange(selfChange);
// 重新更新lockapp集合里面的内容
Log.i(TAG, "-----------数据库内容变化了");
lockapps = dao.getAllApps();
}
}