内容提供者和内容观察者及其应用

内容提供者的实现

1.定义一个类继承ContentProvider类

public class PersonProvider extends ContentProvider {

 

// 定义一个uri匹配器,用于匹配uri,如果匹配不成功返回-1

private static UriMatcher matcher = new UriMatcher(UriMatcher.NO_MATCH);

private static final int INSERT = 1;

private static final int DELETE = 2;

private static final int UPDATE = 3;

private static final int QUERY = 4;

private static final int QUERYONE = 5;

private static final Uri URI = Uri.parse("content://person.db");

 

private PersonSQLiteOpenHelper helper;

 

static {

// 添加一组匹配规则

// authority: the authority to match

// path: the path to match. * may be used as a wild card for any text,

// and # may be used as a wild card for numbers.

// code: the code that is returned when a URI is matched against the

// given components. Must be positive.

matcher.addURI("com.itheima.contentprovider.personprovider", "insert",

INSERT);

matcher.addURI("com.itheima.contentprovider.personprovider", "delete",

DELETE);

matcher.addURI("com.itheima.contentprovider.personprovider", "update",

UPDATE);

matcher.addURI("com.itheima.contentprovider.personprovider", "query",

QUERY);

matcher.addURI("com.itheima.contentprovider.personprovider", "query/#",

QUERYONE);

}

 

@Override

public boolean onCreate() {

this.helper = new PersonSQLiteOpenHelper(getContext());

return false;

}

 

@Override

public Cursor query(Uri uri, String[] projection, String selection,

String[] selectionArgs, String sortOrder) {

if (matcher.match(uri) == QUERY) {

SQLiteDatabase db = helper.getReadableDatabase();

Cursor cursor = db.query("person", projection, selection,

selectionArgs, null, null, sortOrder);

// 注意这里的db和cursor不能关闭

return cursor;

} else if (matcher.match(uri) == QUERYONE) {

SQLiteDatabase db = helper.getReadableDatabase();

long id = ContentUris.parseId(uri);

Cursor cursor = db.query("person", projection, "id=?",

new String[] { id + "" }, null, null, sortOrder);

// 注意这里的db和cursor不能关闭

return cursor;

} else {

throw new IllegalArgumentException("非法uri");

}

}

 

@Override

public int delete(Uri uri, String selection, String[] selectionArgs) {

if (matcher.match(uri) == DELETE) {

SQLiteDatabase db = helper.getWritableDatabase();

// 注册内容观测者

getContext().getContentResolver().notifyChange(URI, null);

return db.delete("person", selection, selectionArgs);

} else {

throw new IllegalArgumentException("非法uri");

}

}

 

@Override

public Uri insert(Uri uri, ContentValues values) {

if (matcher.match(uri) == INSERT) {

SQLiteDatabase db = helper.getWritableDatabase();

long id = db.insert("person", null, values);

getContext().getContentResolver().notifyChange(URI, null);

// 返回指定的Uri路劲对象

// content://cn.itcast.provider.custom.usersprovider/users/1

return ContentUris.withAppendedId(uri, id);

 

} else {

throw new IllegalArgumentException("非法uri");

}

}

 

@Override

public int update(Uri uri, ContentValues values, String selection,

String[] selectionArgs) {

if (matcher.match(uri) == UPDATE) {

SQLiteDatabase db = helper.getWritableDatabase();

getContext().getContentResolver().notifyChange(URI, null);

return db.update("person", values, selection, selectionArgs);

} else {

throw new IllegalArgumentException("非法uri");

}

}

 

/**

 * Implement this to handle requests for the MIME type of the data at the

 * given URI. The returned MIME type should start with

 * vnd.android.cursor.item for a single record, or vnd.android.cursor.dir/

 * for multiple items. This method can be called from multiple threads, as

 * described in Processes and Threads.

 */

@Override

public String getType(Uri uri) {

if (matcher.match(uri) == QUERY) {

return "vnd.android.cursor.dir/person";

} else if (matcher.match(uri) == QUERYONE) {

return "vnd.android.cursor.item/person";

} else {

return "";

}

}

 

}

2.定义一个类继承SQLiteOpenHelper类

public class PersonSQLiteOpenHelper extends SQLiteOpenHelper {

private static final String DBFILENAME = "person.db";

private static int db_version = 1;

 

public PersonSQLiteOpenHelper(Context context) {

super(context, DBFILENAME, null, db_version);

}

 

/**

 * 当数据库第一次创建时调用

 */

@Override

public void onCreate(SQLiteDatabase db) {

String sql = "create table person(id integer primary key autoincrement,name varchar(20),number varchar(20))";

db.execSQL(sql);

}

 

/**

 * 当数据库的版本号发生增加的时候调用

 */

@Override

public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

System.out.println("数据库更改!");

String sql = "alter table person add account varchar(20)";

db.execSQL(sql);

}

 

}

3.清单文件中注册内容提供者

<provider 

            android:name="com.itheima.contentprovider.PersonProvider"

            android:authorities="com.itheima.contentprovider.personprovider"

            ></provider>

 

 

第三方软件

public class OtherappActivity extends Activity {

/** Called when the activity is first created. */

@Override

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.main);

 

}

 

public void getAll(View view) {

ContentResolver resolver = this.getContentResolver();

Uri uri = Uri

.parse("content://com.itheima.contentprovider.personprovider/query");

Cursor cursor = resolver.query(uri, null, null, null, null);

StringBuffer sb = new StringBuffer();

while (cursor.moveToNext()) {

sb.append(cursor.getString(cursor.getColumnIndex("name")) + " -- "

+ cursor.getString(cursor.getColumnIndex("number")));

sb.append("\n");

}

TextView tv_info = (TextView) this.findViewById(R.id.tv_info);

tv_info.setText(sb.toString());

cursor.close();

}

 

public void getOne(View view) {

ContentResolver resolver = this.getContentResolver();

// Uri uri = Uri

// .parse("content://com.itheima.contentprovider.personprovider/query");

// Cursor cursor = resolver.query(uri, null, "id=?",new String[]{"1"} ,

// null);

Uri uri = Uri

.parse("content://com.itheima.contentprovider.personprovider/query/1");

Cursor cursor = resolver.query(uri, null, null, null, null);

StringBuffer sb = new StringBuffer();

if (cursor.moveToFirst()) {

sb.append(cursor.getString(cursor.getColumnIndex("name")) + " -- "

+ cursor.getString(cursor.getColumnIndex("number")));

sb.append("\n");

}

TextView tv_info = (TextView) this.findViewById(R.id.tv_info);

tv_info.setText(sb.toString());

cursor.close();

}

 

 

public void insert(View view) {

ContentResolver resolver = this.getContentResolver();

Uri uri = Uri.parse("content://com.itheima.contentprovider.personprovider/insert");

ContentValues values = new ContentValues();

values.put("name", "reality");

values.put("number", "567");

Uri result = resolver.insert(uri, values);

System.out.println("result = " +result);

}

 

public void update(View view) {

ContentResolver resolver = this.getContentResolver();

Uri uri = Uri.parse("content://com.itheima.contentprovider.personprovider/update");

ContentValues values = new ContentValues();

values.put("name", "dog");

values.put("number", "110");

int result = resolver.update(uri, values, "id=?", new String[]{"1"});

System.out.println("result = " +result);

}

 

public void delete(View view) {

ContentResolver resolver = this.getContentResolver();

Uri uri = Uri.parse("content://com.itheima.contentprovider.personprovider/delete");

int result = resolver.delete(uri, "id=?", new String[]{"3"});

System.out.println("result = " + result);

}

}

短信的备份

1.Activity

public class BackupsmsActivity extends Activity {

/** Called when the activity is first created. */

@Override

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.main);

}

 

public void backupSMS(View view) {

Uri uri = Uri.parse("content://sms");

ContentResolver resolver = this.getContentResolver();

Cursor cursor = resolver.query(uri, new String[]{"date","body","address","type"}, null, null, null);

ArrayList<SmsInfo> infos = new ArrayList<SmsInfo>();

while(cursor.moveToNext()){

long date = cursor.getLong(0);

String body = cursor.getString(1);

String address = cursor.getString(2);

int type = cursor.getInt(3);

SmsInfo smsInfo = new SmsInfo(date, body, address, type);

infos.add(smsInfo);

}

SmsUtil.save(this, infos);

}

}

2.工具类

public class SmsUtil {

public static void save(Context context, ArrayList<SmsInfo> infos) {

XmlSerializer xmlSerializer = Xml.newSerializer();

File file = new File(Environment.getExternalStorageDirectory(),

"sms_bak.xml");

try {

FileOutputStream fos = new FileOutputStream(file);

xmlSerializer.setOutput(fos, "utf-8");

xmlSerializer.startDocument("utf-8", true);

 

xmlSerializer.startTag(null, "smss");

 

for (SmsInfo info : infos) {

xmlSerializer.startTag(null, "sms");

xmlSerializer.attribute(null, "type", info.getType() + "");

 

xmlSerializer.startTag(null, "date");

xmlSerializer.text(info.getDate() + "");

xmlSerializer.endTag(null, "date");

 

xmlSerializer.startTag(null, "address");

xmlSerializer.text(info.getAddress());

xmlSerializer.endTag(null, "address");

 

xmlSerializer.startTag(null, "body");

xmlSerializer.text(info.getBody());

xmlSerializer.endTag(null, "body");

 

xmlSerializer.endTag(null, "sms");

}

xmlSerializer.endTag(null, "smss");

 

xmlSerializer.endDocument();

fos.close();

Toast.makeText(context, "保存成功", 0).show();

 

} catch (Exception e) {

e.printStackTrace();

Toast.makeText(context, "保存失败", 0).show();

}

 

}

}

 

3.实体类

public class SmsInfo {

private int id;

private long date;

private String body;

private String address;

private int type;

 

public SmsInfo() {

super();

// TODO Auto-generated constructor stub

}

 

public SmsInfo(int id, long date, String body, String address) {

super();

this.id = id;

this.date = date;

this.body = body;

this.address = address;

}

 

public SmsInfo(long date, String body, String address, int type) {

super();

this.date = date;

this.body = body;

this.address = address;

this.type = type;

}

 

public int getType() {

return type;

}

 

public void setType(int type) {

this.type = type;

}

 

public int getId() {

return id;

}

 

public void setId(int id) {

this.id = id;

}

 

public long getDate() {

return date;

}

 

public void setDate(long date) {

this.date = date;

}

 

public String getBody() {

return body;

}

 

public void setBody(String body) {

this.body = body;

}

 

public String getAddress() {

return address;

}

 

public void setAddress(String address) {

this.address = address;

}

 

}

4.授权

<uses-permission android:name="android.permission.WRITE_SMS"/>

<uses-permission android:name="android.permission.READ_SMS"/>

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

 

插入一条记录到系统短信应用

public class InsertsmsActivity extends Activity {

    /** Called when the activity is first created. */

    @Override

    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.main);

        new Thread(){

        public void run(){

        try {

Thread.sleep(10000);

Uri uri = Uri.parse("content://sms");

ContentResolver resolver = getContentResolver();

ContentValues values = new ContentValues();

values.put("address", "10086");

values.put("type", 1);

values.put("date", System.currentTimeMillis());

values.put("body", "您的余额还有100,000,000元!");

 

resolver.insert(uri, values);

} catch (InterruptedException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

        }

        

        }.start();

    }

}

<uses-permission android:name="android.permission.READ_SMS"/>

<uses-permission android:name="android.permission.WRITE_SMS"/>

 内容观察者

public class MainActivity extends Activity {

private static final Uri URI= Uri.parse("content://person.db");

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

ContentResolver resolver  = this.getContentResolver();

/**

 * If true changes to URIs beginning with uri will also cause notifications to be sent. 

 * If false only changes to the exact URI specified by uri will cause notifications to be sent. 

 * If true, than any URI values at or below the specified URI will also trigger a match.

 */

 resolver.registerContentObserver(URI, true, new MyObserver(new Handler()));

}

 

private class MyObserver extends ContentObserver{

 

public MyObserver(Handler handler) {

super(handler);

// TODO Auto-generated constructor stub

}

 

@Override

public void onChange(boolean selfChange) {

super.onChange(selfChange);

Toast.makeText(MainActivity.this, "数据库内容发送变化了!", 0).show();

}

 

 

}

}

 

posted on 2012-10-10 09:21  Freedom000  阅读(220)  评论(0编辑  收藏  举报

导航