【Android 简单通信组件学习】ContentProvide 唯一与所有app交互的组件
2016-12-25 13:37
561 查看
首先我们了解
ContentProvider组件
它 实现系统数据访问
实现应用程序数据共享
补充一:
ContentProvider -数据提供者,
是Android四大组件之一,是程序之间数据共享的接口
Activity系统中对数据的访问限制是非常严格的,
不允许其他应用直接访问当前程序中存储在非SD卡中数据,
但是实际中我们经常会涉及到数据共享,
ContentProvider则是应用程序提供为外部访问的一个窗户,
为数据共享提供了统一的访问方法
补充二:
ContentProvide对数据进行封装,不用关心数据存储的细节。使用表的形式来组织数据
ContentProvider可以在不同的应用程序之间共享数据
Android为常见的一些数据提供了默认的ContentProvider(包括音频、视频、图片和通讯录等)
补充三:方法
1、ContentProvider类主要方法的作用:
public boolean onCreate():
该方法在ContentProvider创建后就会被调用,Android开机后,ContentProvider在其它应用第一次访问它时才会被创建。
public Uri insert(Uri uri, ContentValues values):
供外部ContentProvider添加数据。 public int delete(Uri uri, String selection, String[] selectionArgs):
该方法用于供外部应用从ContentProvider删除数据。
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs):
该方法用于供外部应用更新ContentProvider中的数据。
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder)
用于供外部应用从ContentProvider中获取数据。 public String getType(Uri uri):用于返回当前Url所代表数据的MIME类型。
如果操作的数据属于集合类型,那么MIME类型字符串应该以vnd.android.cursor.dir/开头
补充四:
1、ContentResolver操作ContentProvider中的数据
当外部应用需要对ContentProvider中的数据进行添加、删除、修改和查询操作时,可以使用ContentResolver 类来完成,要获取ContentResolver 对象,可以使用Activity提供的getContentResolver()方法
监听ContentProvider中数据的变化
如果ContentProvider的访问者需要知道ContentProvider中的数据发生变化,
可以在ContentProvider发生数据变化时调用getContentResolver().notifyChange(uri, null)
来通知注册在此URI上的访问者
例子:
QQ访问sd卡,读取图片,发送表情。
微信 访问通讯录,生成新的好友信息
代码效果:
一、添加学生:
查询学生:添加了几个,就能查询出几个
访问数据信息:
这里有2个,读取短信息的 eclipse从控制台输入信息试试,可以的
studio 的自行开第二个虚拟机发送短信
读取通讯录:抱歉啊,虚拟机没有安装输入法,不打中文了
虽然排序的不是很整齐,还有些疵瑕。
代码的组成:
公布代码:
一、MainActivity.java
activity_main.xml
二、SmsActivity.java
ContentProvider组件
它 实现系统数据访问
实现应用程序数据共享
补充一:
ContentProvider -数据提供者,
是Android四大组件之一,是程序之间数据共享的接口
Activity系统中对数据的访问限制是非常严格的,
不允许其他应用直接访问当前程序中存储在非SD卡中数据,
但是实际中我们经常会涉及到数据共享,
ContentProvider则是应用程序提供为外部访问的一个窗户,
为数据共享提供了统一的访问方法
补充二:
ContentProvide对数据进行封装,不用关心数据存储的细节。使用表的形式来组织数据
ContentProvider可以在不同的应用程序之间共享数据
Android为常见的一些数据提供了默认的ContentProvider(包括音频、视频、图片和通讯录等)
补充三:方法
1、ContentProvider类主要方法的作用:
public boolean onCreate():
该方法在ContentProvider创建后就会被调用,Android开机后,ContentProvider在其它应用第一次访问它时才会被创建。
public Uri insert(Uri uri, ContentValues values):
供外部ContentProvider添加数据。 public int delete(Uri uri, String selection, String[] selectionArgs):
该方法用于供外部应用从ContentProvider删除数据。
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs):
该方法用于供外部应用更新ContentProvider中的数据。
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder)
用于供外部应用从ContentProvider中获取数据。 public String getType(Uri uri):用于返回当前Url所代表数据的MIME类型。
如果操作的数据属于集合类型,那么MIME类型字符串应该以vnd.android.cursor.dir/开头
补充四:
1、ContentResolver操作ContentProvider中的数据
当外部应用需要对ContentProvider中的数据进行添加、删除、修改和查询操作时,可以使用ContentResolver 类来完成,要获取ContentResolver 对象,可以使用Activity提供的getContentResolver()方法
监听ContentProvider中数据的变化
如果ContentProvider的访问者需要知道ContentProvider中的数据发生变化,
可以在ContentProvider发生数据变化时调用getContentResolver().notifyChange(uri, null)
来通知注册在此URI上的访问者
例子:
QQ访问sd卡,读取图片,发送表情。
微信 访问通讯录,生成新的好友信息
代码效果:
一、添加学生:
查询学生:添加了几个,就能查询出几个
访问数据信息:
这里有2个,读取短信息的 eclipse从控制台输入信息试试,可以的
studio 的自行开第二个虚拟机发送短信
读取通讯录:抱歉啊,虚拟机没有安装输入法,不打中文了
虽然排序的不是很整齐,还有些疵瑕。
代码的组成:
公布代码:
一、MainActivity.java
package com.open_open.android_ch13contentprovide; import android.app.Activity; import android.content.ContentValues; import android.content.Intent; import android.database.Cursor; import android.os.Bundle; import android.view.View; import android.widget.Toast; import com.open_open.android_ch13contentprovide.utils.DbUtils; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } //添加学生 public void addStu(View view){ ContentValues values=new ContentValues(); values.put("sname","Toms"+Math.round(Math.random()*100)); values.put("sage",28); values.put("ssex","男"); long id=new DbUtils(this).insert("stu",values); Toast.makeText(this,"添加完毕,学生ID:"+id,5000).show(); } public void findStu(View view){ Cursor cursor = new DbUtils(this).query("stu",null,null,null,null,null,null); while (cursor.moveToNext()){ Toast.makeText(this,"姓名:"+cursor.getString(1),3000).show(); } cursor.close(); } public void doSystemData(View view){ Intent intent= new Intent(this,SmsActivity.class); startActivity(intent); } }
activity_main.xml
<?xml version="1.0" encoding="utf-8"?> <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" > <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:text="添加学生" android:textSize="28sp" android:onClick="addStu" /> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:text="查询学生" android:textSize="28sp" android:onClick="findStu" /> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:text="访问系统数据" android:textSize="28sp" android:onClick="doSystemData" /> </LinearLayout>
二、SmsActivity.java
public class SmsActivity extends AppCompatActivity { private EditText showMessage; private ContentResolver resolver; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_sms); showMessage=(EditText)findViewById(R.id.showMessage); resolver=getContentResolver(); } //读取短信 public void readSms(View view){ Uri uri=Uri.parse("content://sms"); String[] selectItem={"address","date","read","body"}; Cursor cursor=resolver.query(uri,selectItem,null,null,null); String[] cols=cursor.getColumnNames(); StringBuffer sb=new StringBuffer(); while (cursor.moveToNext()){ for (int i = 0; i <cols.length; i++) { sb.append(cols[i]+"="+cursor.getString(i)+","); } sb.append("\n"); } showMessage.setText(sb.toString()); cursor.close(); } //读取通讯录 public void readTelephone(View view){ Uri uri= ContactsContract.Contacts.CONTENT_URI; Uri uri2= ContactsContract.CommonDataKinds.Phone.CONTENT_URI; Cursor cursor=resolver.query(uri,new String[]{"_id","display_name"},null,null,null); String[] cols=cursor.getColumnNames(); StringBuffer sb=new StringBuffer(); while (cursor.moveToNext()){ for (int i = 0; i <cols.length ; i++) { sb.append(cols[i]+"="+cursor.getString(i)+","); Cursor c2=resolver.query(uri2,new String[]{"data1"},"_id=" +cursor.getInt(0),null,null); String[] col2=c2.getColumnNames(); while (c2.moveToNext()){ for (int j = 0; j <col2.length ; j++) { sb.append(col2[j]+"="+c2.getString(j)+","); } } } sb.append("\n"); } showMessage.setText(sb.toString()); cursor.close(); } }package com.open_open.android_ch13contentprovide; import android.content.ContentResolver; import android.database.Cursor; import android.net.Uri; import android.provider.ContactsContract; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.EditText;public class SmsActivity extends AppCompatActivity { private EditText showMessage; private ContentResolver resolver; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_sms); showMessage=(EditText)findViewById(R.id.showMessage); resolver=getContentResolver(); } //读取短信 public void readSms(View view){ Uri uri=Uri.parse("content://sms"); String[] selectItem={"address","date","read","body"}; Cursor cursor=resolver.query(uri,selectItem,null,null,null); String[] cols=cursor.getColumnNames(); StringBuffer sb=new StringBuffer(); while (cursor.moveToNext()){ for (int i = 0; i <cols.length; i++) { sb.append(cols[i]+"="+cursor.getString(i)+","); } sb.append("\n"); } showMessage.setText(sb.toString()); cursor.close(); } //读取通讯录 public void readTelephone(View view){ Uri uri= ContactsContract.Contacts.CONTENT_URI; Uri uri2= ContactsContract.CommonDataKinds.Phone.CONTENT_URI; Cursor cursor=resolver.query(uri,new String[]{"_id","display_name"},null,null,null); String[] cols=cursor.getColumnNames(); StringBuffer sb=new StringBuffer(); while (cursor.moveToNext()){ for (int i = 0; i <cols.length ; i++) { sb.append(cols[i]+"="+cursor.getString(i)+","); Cursor c2=resolver.query(uri2,new String[]{"data1"},"_id=" +cursor.getInt(0),null,null); String[] col2=c2.getColumnNames(); while (c2.moveToNext()){ for (int j = 0; j <col2.length ; j++) { sb.append(col2[j]+"="+c2.getString(j)+","); } } } sb.append("\n"); } showMessage.setText(sb.toString()); cursor.close(); } }
activity_sms.xml<?xml version="1.0" encoding="utf-8"?> <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"> <EditText android:id="@+id/showMessage" android:layout_width="match_parent" android:layout_height="wrap_content" android:inputType="textMultiLine" android:text="暂时没有数据显示" /> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:text="读取短信息" android:onClick="readSms"/> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:text="读取通讯录" android:onClick="readTelephone"/> </LinearLayout>
三、provider 包:MyProvider.javapackage com.open_open.android_ch13contentprovide.provider; import android.content.ContentProvider; import android.content.ContentUris; import android.content.ContentValues; import android.content.UriMatcher; import android.database.Cursor; import android.net.Uri; import com.open_open.android_ch13contentprovide.utils.DbUtils; /** * Created by Administrator on 2016/12/15. */ public class MyProvider extends ContentProvider{ //定义几个常量用来充当URI标示值 private static final int STUS=1; private static final int STU=2; //构建URI匹配对象 private static UriMatcher matcher=new UriMatcher (UriMatcher.NO_MATCH); //构建匹配项,/#:ID为# static{ matcher.addURI("com.open_open.android_ch13contentprovide", "stu", STUS); matcher.addURI("com.open_open.android_ch13contentprovide", "stu/#", STU); } private DbUtils dbUtils; //初始化工作 @Override public boolean onCreate() { //获取操作数据库的工具类 dbUtils=new DbUtils(this.getContext()); return false; } //公共的查询接口 @Override public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { switch (matcher.match(uri)) { case STUS: return dbUtils.query("stu", projection, selection, selectionArgs, null, null, sortOrder); case STU: long id= ContentUris.parseId(uri);//从URI取出要查询数据的ID String where="_id="+id; if(selection!=null){ //查询有条件where=selection+" and "+where; } return dbUtils.query("stu", projection, where, selectionArgs, null, null, sortOrder); default: break; } return null; } @Override public String getType(Uri uri) { switch (matcher.match(uri)) { case STUS: return "vnd.android.cursor.dir/stu"; //dir:目录列表 case STU: return "vnd.android.cursor.item/stu"; //item:一个项目 default: break; } return null; } @Override public Uri insert(Uri uri, ContentValues values) { if(matcher.match(uri)==STUS){ long id=dbUtils.insert("stu", values); //在uri后面追加一个ID部分 return ContentUris.withAppendedId(uri, id); } return null; } @Override public int delete(Uri uri, String selection, String[] selectionArgs) { switch (matcher.match(uri)) { case STUS: int c=dbUtils.delete("stu", selection, selectionArgs); return c; case STU: long id=ContentUris.parseId(uri); String where="_id="+id; if(selection!=null){ where=selection+" and "+where; } int c2=dbUtils.delete("stu", where, selectionArgs); return c2; default: break; } return 0; } @Override public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) { switch (matcher.match(uri)) { case STUS: long i=dbUtils.update("stu", values, selection, selectionArgs); return (int)i; case STU: long id=ContentUris.parseId(uri); String where="_id="+id; if(selection!=null){ where=selection+" and "+where; } long i2=dbUtils.update("stu", values, where, selectionArgs); return (int)i2; default: break; } return 0; } }
四、utils 包 :
DbHelper.javapackage com.open_open.android_ch13contentprovide.utils; import android.content.Context; import android.database.DatabaseErrorHandler; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; /** * Created by Administrator on 2016/12/15. */ public class DbHelper extends SQLiteOpenHelper{ public DbHelper(Context context) { super(context, "mydb.db", null, 1); } @Override public void onCreate(SQLiteDatabase db) { //建表:注意:_id 中不能大写!否则无法识别 String sql="create table if not exists stu(" + "_id integer primary key," + "sname text," + "sage integer," + "ssex text" + ")"; db.execSQL(sql); //插入第一条数据 sql="insert into stu(sname,sage,ssex) values('xiaoming',23,'男')"; //插入第二条数据 db.execSQL(sql); sql="insert into stu(sname,sage,ssex) values('Lucy',23,'女')"; db.execSQL(sql); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { String sql="drop table stu"; db.execSQL(sql); onCreate(db); } }
DbUtils.java (sql添加,更新,删除,查询的方法)package com.open_open.android_ch13contentprovide.utils; import android.content.Context; import android.content.ContentValues; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; /** * Created by Administrator on 2016/12/15. */ public class DbUtils { private Context ctx; private SQLiteDatabase sdb; public DbUtils(Context ctx){ this.ctx=ctx; sdb=new DbHelper(ctx).getReadableDatabase(); } //插入 public long insert(String tableName,ContentValues values){ long id=sdb.insert(tableName,null,values); return id; } //更新 public long update(String table,ContentValues values,String wherClause ,String[] whereArgs){ long id=sdb.update(table,values,wherClause,whereArgs); return id; } //删除 public int delete(String table,String whereClause,String[] whereArgs){ int count=sdb.delete(table,whereClause,whereArgs); return count; } //查询 public Cursor query(String table,String[] columns,String selection,String[] selectionArgs,String groupBy,String having,String orderBy){ Cursor cursor=sdb.query(table,columns,selection,selectionArgs,groupBy,having,orderBy); return cursor; } }
其他:AndroidMainfest.xml
<!-- 权限开启! -->
<uses-permission android:name="android.permission.WRITE_SMS"/>
<uses-permission android:name="android.permission.READ_SMS"/>
<uses-permission android:name="android.permission.READ_CONTACTS"/>
public class SmsActivity extends AppCompatActivity { private EditText showMessage; private ContentResolver resolver; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_sms); showMessage=(EditText)findViewById(R.id.showMessage); resolver=getContentResolver(); } //读取短信 public void readSms(View view){ Uri uri=Uri.parse("content://sms"); String[] selectItem={"address","date","read","body"}; Cursor cursor=resolver.query(uri,selectItem,null,null,null); String[] cols=cursor.getColumnNames(); StringBuffer sb=new StringBuffer(); while (cursor.moveToNext()){ for (int i = 0; i <cols.length; i++) { sb.append(cols[i]+"="+cursor.getString(i)+","); } sb.append("\n"); } showMessage.setText(sb.toString()); cursor.close(); } //读取通讯录 public void readTelephone(View view){ Uri uri= ContactsContract.Contacts.CONTENT_URI; Uri uri2= ContactsContract.CommonDataKinds.Phone.CONTENT_URI; Cursor cursor=resolver.query(uri,new String[]{"_id","display_name"},null,null,null); String[] cols=cursor.getColumnNames(); StringBuffer sb=new StringBuffer(); while (cursor.moveToNext()){ for (int i = 0; i <cols.length ; i++) { sb.append(cols[i]+"="+cursor.getString(i)+","); Cursor c2=resolver.query(uri2,new String[]{"data1"},"_id=" +cursor.getInt(0),null,null); String[] col2=c2.getColumnNames(); while (c2.moveToNext()){ for (int j = 0; j <col2.length ; j++) { sb.append(col2[j]+"="+c2.getString(j)+","); } } } sb.append("\n"); } showMessage.setText(sb.toString()); cursor.close(); } }
相关文章推荐
- Android系列学习讲座之五--App布局初探之简单模型
- Android客户端与数据库交互数据的简单学习
- 使用Event Bus模式解耦Android App组件间通信
- android菜鸟学习笔记25----与服务器端交互(二)解析服务端返回的json数据及使用一个开源组件请求服务端数据
- Android学习系列(5)--App布局初探之简单模型【转】
- 使用Event Bus模式解耦Android App组件间通信
- 跨进程(同一app不同进程之间通信)——Android自动化测试学习历程
- 【android】使用Event Bus模式解耦Android App组件间通信
- 通过实例简单讲解Android App中的Activity组件
- android组件间的交互和进程间IPC通信
- 使用Event Bus模式解耦Android App组件间通信
- 使用Event Bus模式解耦Android App组件间通信
- Android组件间通信库EventBus学习观察者模式
- android学习—— 简单的实现 android 退出app 的功能, 非 restartPackage
- 使用Event Bus模式解耦Android App组件间通信
- Android组件间通信库EventBus学习
- Android 交互功能组件BroadcastReceiver 的简单使用
- android初步学习时所有简单例子整合到一个ListView上
- android组件间的交互和进程间IPC通信
- Android学习一——动态添加组件与删除,可见性设置,imagebutton简单使用