观察者

在内容提供者的基础上,若有数据放生变化,则通知其他应用

package com.shz.observer;

import android.app.Activity;
import android.app.ActionBar;
import android.app.Fragment;
import android.content.ContentResolver;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.os.Build;

public class MainActivity extends Activity {

    public static final String TAG = "testobserver";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        //Uri uri = Uri.parse("content://db.personprovider/insert");
        Uri uri = Uri.parse("content://db.personprovider/");
        this.getContentResolver().registerContentObserver(uri, true,new MyObserver(null));
    }

    private class MyObserver extends ContentObserver
    {

        public MyObserver(Handler handler) {
            super(handler);
        }

        @Override
        public void onChange(boolean selfChange) {
            Uri uri = Uri.parse("content://db.personprovider/query");
            ContentResolver resolver = getApplicationContext().getContentResolver();
            Cursor c = resolver.query(uri, null, null, null, "id desc");
            
            if(c.moveToFirst())
            {
                Log.i(TAG, "插入的新记录name:"+c.getString(c.getColumnIndex("name")));
            }
            else
            {
                Log.i(TAG, "未监听到A应用的数据发生改变");
            }
        }
        
        
        
    }
}

 

posted @ 2014-08-11 22:02  萌浩  阅读(137)  评论(0编辑  收藏  举报