android学习笔记一(基础部分)

工程:
Phone、Sms (短信、单元测试)、File(存储文件、sdcard文件存储)、Other(访问file项目中的文件、AccessOtherAppPreferenceTest访问Preferences)、XML、SoftPreferences

权限:

1、添加权限方式
AndroidManifest.xml中添加电话服务权限:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="cn.nbchina.action"
android:versionCode="1"
android:versionName="1.0">
略....
<uses-sdk android:minSdkVersion=“6" />
<uses-permission android:name="android.permission.CALL_PHONE"/>
</manifest>

2、权限种类
<!-- 在SDCard中创建与删除文件权限 -->
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
<!-- 往SDCard写入数据权限 -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<!-- 电话服务权限 -->
<uses-permission android:name="android.permission.CALL_PHONE"/>
<!--短信服务权限-->

<uses-permission android:name="android.permission.SEND_SMS"/>
<!--单元测试权限-->

<application ....>
<uses-library android:name="android.test.runner" />
....
</application>
<instrumentation android:name="android.test.InstrumentationTestRunner"
android:targetPackage="cn.nbchina.action" android:label="Tests for My App" />



三种通知方式:
1、状态栏通知 ppt93页
2、对话框通知 ppt94页
3、土司通知(Toast)

Toast.makeText(SmsActivity.this, R.string.success, Toast.LENGTH_LONG).show();


信息输出:


show view-->

Devices 管理设备
LogCat 查看输出信息 android输出日志信息。
输出级别(i:info;d:debug;e:error;w:warn)
Log.i(tag,输出内容); tag标签,一般使用测试代码所在类的类名作为标签。
一般定一个常量 private static final String TAG = "PersonServiceTest";
Log.i(TAG,输出内容);
System.out.println 也可向控制台输出信息 级别info


界面布局:

LinearLayout (线性布局)、AbsoluteLayout(绝对布局)、RelativeLayout(相对布局)、TableLayout(表格布局)、FrameLayout(帧布局)

[html] view plain copy print ?
 
  1. <?xmlversion="1.0"encoding="utf-8"?>
  2. <LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
  3. android:orientation="vertical"
  4. android:layout_width="fill_parent"
  5. android:layout_height="fill_parent">
  6. <TextView
  7. android:layout_width="fill_parent"android:layout_height="wrap_content"
  8. android:text="@string/inputmobile"/>
  9. <EditTextandroid:layout_width="fill_parent"android:layout_height="wrap_content"
  10. android:id="@+id/mobile"/>
  11. <Buttonandroid:layout_width="wrap_content"android:layout_height="wrap_content"
  12. android:text="@string/button"
  13. android:id="@+id/button"/>
  14. </LinearLayout>




布局几种方式
1、LinearLayout (线性布局)
2、AbsoluteLayout(绝对布局) 不建议使用
3、RelativeLayout(相对布局)
4、TableLayout(表格布局)
5、FrameLayout(帧布局) 以屏幕左上角坐标为叠加,一个个画面叠加,主要使用在动画场合。比如一个视频,鼠标移动到上面,就会出现一个画面。这就是利用了帧布局


布局实例参考file:///D:/android-sdk-windows/docs/guide/topics/ui/layout-objects.html

Dev Guide项 下的Framework Topics -->User interface -->Common Layout Objects
可查看到这几种布局的实例代码


列 相对布局


[html] view plain copy print ?
 
  1. <?xmlversion="1.0"encoding="utf-8"?>
  2. <RelativeLayoutxmlns:android="http://schemas.android.com/apk/res/android
  3. android:layout_width="fill_parent"
  4. android:layout_height="wrap_content"
  5. android:background="@drawable/blue"
  6. android:padding="10px">
  7. <TextViewandroid:id="@+id/label"
  8. android:layout_width="fill_parent"
  9. android:layout_height="wrap_content"
  10. android:text="Typehere:"/>
  11. <EditTextandroid:id="@+id/entry"
  12. android:layout_width="fill_parent"
  13. android:layout_height="wrap_content"
  14. android:background="@android:drawable/editbox_background"
  15. android:layout_below="@id/label"/>
  16. <Buttonandroid:id="@+id/ok"
  17. android:layout_width="wrap_content"
  18. android:layout_height="wrap_content"
  19. android:layout_below="@id/entry"
  20. android:layout_alignParentRight="true"
  21. android:layout_marginLeft="10px"
  22. android:text="OK"/>
  23. <Buttonandroid:layout_width="wrap_content"
  24. android:layout_height="wrap_content"
  25. android:layout_toLeftOf="@id/ok"
  26. android:layout_alignTop="@id/ok"
  27. android:text="Cancel"/>
  28. </RelativeLayout>




单元测试:
AndroidManifest.xml文件中添加权限

[java] view plain copy print ?
 
  1. packagecom.nbchina.service;
  2. publicclassPersonService{
  3. publicintsave(){
  4. Stringin="78";
  5. intb=newInteger(in);
  6. returnb;
  7. }
  8. }



上面targetPackage指定的包要和应用的package相同。
第二步:编写单元测试代码(选择要测试的方法,右键点击“Run As”--“Android Junit Test” ):

[java] view plain copy print ?
 
  1. packagecom.nbchina.test;
  2. importjunit.framework.Assert;
  3. importcom.nbchina.service.PersonService;
  4. importandroid.test.AndroidTestCase;
  5. importandroid.util.Log;
  6. publicclassPersonServiceTestextendsAndroidTestCase{
  7. privatestaticfinalStringTAG="PersonServiceTest";
  8. publicvoidtestSave()throwsThrowable{
  9. PersonServiceservice=newPersonService();
  10. intb=service.save();//检验save()方法运行是否正常
  11. Log.i(TAG,"result="+b);
  12. //System.out.println();
  13. //System.err.println("result="+b);
  14. //Assert.assertEquals(738,b);
  15. }
  16. }



[plain] view plain copy print ?
 
  1. MV
  2. Service
  3. C—Activity
  4. V—main.xml




Android中的显示单位


px (pixels)像素
一般HVGA代表320x480像素,这个用的比较多。

dip或dp (device independent pixels)设备独立像素
这个和设备硬件有关,一般为了支持WVGA、HVGA和QVGA 推荐使用这个,不依赖像素。

sp (scaled pixels — best for text size)比例像素
主要处理字体的大小,可以根据系统的字体自适应。

为了适应不同分辨率,不同的像素密度,推荐使用dip ,文字使用sp。




数据存储与访问:
以下五种:
1、文件
2、SharedPreferences(参数)
3、SQLite数据库
4、内容提供者(Content provider)
5、网络




文件的权限:
Context.MODE_PRIVATE:为默认操作模式,代表该文件是私有数据,只能被应用本身访问,在该模式下,写入的内容会覆盖原文件的内容,如果想把新写入的内容追加到原文件中。可以使用Context.MODE_APPEND
Context.MODE_APPEND:模式会检查文件是否存在,存在就往文件追加内容,否则就创建新文件。
Context.MODE_WORLD_READABLE和Context.MODE_WORLD_WRITEABLE用来控制其他应用是否有权限读写该文件。
MODE_WORLD_READABLE:表示当前文件可以被其他应用读取;MODE_WORLD_WRITEABLE:表示当前文件可以被其他应用写入。
如果希望文件被其他应用读和写,可以传入:
openFileOutput("nbchina.txt", Context.MODE_WORLD_READABLE + Context.MODE_WORLD_WRITEABLE);
Activity还提供了getCacheDir()和getFilesDir()方法:
getCacheDir()方法用于获取/data/data/<package name>/cache目录
getFilesDir()方法用于获取/data/data/<package name>/files目录



SDCard存放文件:
要往SDCard存放文件,程序必须先判断手机是否装有SDCard,并且可以进行读写。
注意:访问SDCard必须在AndroidManifest.xml中加入访问SDCard的权限

[java] view plain copy print ?
 
  1. if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
  2. FilesdCardDir=Environment.getExternalStorageDirectory();//获取SDCard目录
  3. FilesaveFile=newFile(sdCardDir,“nbchina.txt”);
  4. FileOutputStreamoutStream=newFileOutputStream(saveFile);
  5. outStream.write("笔记本中国".getBytes());
  6. outStream.close();
  7. }



Environment.getExternalStorageState()方法用于获取SDCard的状态,如果手机装有SDCard,并且可以进行读写,那么方法返回的状态等于Environment.MEDIA_MOUNTED。




在Android平台上可以使用Simple API for XML(SAX) 事件驱动、 Document Object Model(DOM)和Android附带的事件驱动 pull解析器解析XML文件。


推荐使用pull
具体使用方式见代码。


SharedPreferences

主要用于保存软件参数,其背后是用xml文件存放数据,文件存放在/data/data/<package name>/shared_prefs目录下

访问SharedPreferences中的数据代码如下:
SharedPreferences sharedPreferences = getSharedPreferences("nbchina", Context.MODE_PRIVATE);
//getString()第二个参数为缺省值,如果preference中不存在该key,将返回缺省值
String name = sharedPreferences.getString("name", "");
int age = sharedPreferences.getInt("age", 1);

如果访问其他应用中的Preference,前提条件是:该preference创建时指定了Context.MODE_WORLD_READABLE或者Context.MODE_WORLD_WRITEABLE权限。如:有个<package name>为cn.nbchina.action的应用使用下面语句创建了preference。
getSharedPreferences("nbchina", Context.MODE_WORLD_READABLE);
其他应用要访问上面应用的preference,首先需要创建上面应用的Context,然后通过Context 访问preference ,访问preference时会在应用所在包下的shared_prefs目录找到preference :
Context otherAppsContext = createPackageContext("cn.nbchina.action", Context.CONTEXT_IGNORE_SECURITY);
SharedPreferences sharedPreferences = otherAppsContext.getSharedPreferences("nbchina", Context.MODE_WORLD_READABLE);
String name = sharedPreferences.getString("name", "");
int age = sharedPreferences.getInt("age", 0);

参考Other工程的AccessOtherAppPreferenceTest代码




嵌入式关系型SQLite数据库存储数据



为了实现对数据库版本进行管理,SQLiteOpenHelper类提供了两个重要的方法,分别是onCreate(SQLiteDatabase db)和onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion),前者用于初次使用软件时生成数据库表,后者用于升级软件时更新数据库表结构。当调用SQLiteOpenHelper的getWritableDatabase()或者getReadableDatabase()方法获取用于操作数据库的SQLiteDatabase实例的时候,如果数据库不存在,Android系统会自动生成一个数据库,接着调用onCreate()方法,onCreate()方法在初次生成数据库时才会被调用,在onCreate()方法里可以生成数据库表结构及添加一些应用使用到的初始化数据。onUpgrade()方法在数据库的版本发生变化时会被调用,一般在软件升级时才需改变版本号,而数据库的版本是由程序员控制的,假设数据库现在的版本是1,由于业务的变更,修改了数据库表结构,这时候就需要升级软件,升级软件时希望更新用户手机里的数据库表结构,为了实现这一目的,可以把原来的数据库版本设置为2(有同学问设置为3行不行?当然可以,如果你愿意,设置为100也行),并且在onUpgrade()方法里面实现表结构的更新。当软件的版本升级次数比较多,这时在onUpgrade()方法里面可以根据原版号和目标版本号进行判断,然后作出相应的表结构及数据更新。


SQLiteOpenHelper对数据库进行版本管理

[java] view plain copy print ?
 
  1. publicclassDatabaseHelperextendsSQLiteOpenHelper{
  2. //类没有实例化,是不能用作父类构造器的参数,必须声明为静态
  3. privatestaticfinalStringname="itcast";//数据库名称
  4. privatestaticfinalintversion=1;//数据库版本
  5. publicDatabaseHelper(Contextcontext){
  6. //第三个参数CursorFactory指定在执行查询时获得一个游标实例的工厂类,设置为null,代表使用系统默认的工厂类
  7. super(context,name,null,version);
  8. }
  9. @OverridepublicvoidonCreate(SQLiteDatabasedb){
  10. db.execSQL("CREATETABLEIFNOTEXISTSperson(personidintegerprimarykeyautoincrement,namevarchar(20),ageINTEGER)");
  11. }
  12. @OverridepublicvoidonUpgrade(SQLiteDatabasedb,intoldVersion,intnewVersion){
  13. db.execSQL("DROPTABLEIFEXISTSperson");
  14. onCreate(db);
  15. }
  16. }



上面onUpgrade()方法在数据库版本每次发生变化时都会把用户手机上的数据库表删除,然后再重新创建。一般在实际项目中是不能这样做的,正确的做法是在更新数据库表结构时,还要考虑用户存放于数据库中的数据不会丢失。


创建数据库与添删改查操作、事务操作参考实例代码


数据显示
使用ListView组件
Item.xml

[java] view plain copy print ?
 
  1. <?xmlversion="1.0"encoding="utf-8"?>
  2. <LinearLayout
  3. xmlns:android="http://schemas.android.com/apk/res/android"
  4. android:orientation="horizontal"
  5. android:layout_width="fill_parent"
  6. android:layout_height="wrap_content">
  7. <!--android:orientation="horizontal"水平-->
  8. <!--android:layout_width="fill_parent"宽度填充-->
  9. <!--android:layout_height="wrap_content"高度包裹-->
  10. <TextView
  11. android:layout_width="80dip"
  12. android:layout_height="wrap_content"
  13. android:text="435"
  14. android:id="@+id/id"
  15. />
  16. <TextView
  17. android:layout_width="100dip"
  18. android:layout_height="wrap_content"
  19. android:text="liming"
  20. android:id="@+id/name"
  21. />
  22. <TextView
  23. android:layout_width="fill_parent"
  24. android:layout_height="wrap_content"
  25. android:text="45"
  26. android:id="@+id/amount"
  27. />
  28. </LinearLayout>




Main.xml

[java] view plain copy print ?
 
  1. <?xmlversion="1.0"encoding="utf-8"?>
  2. <LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
  3. android:orientation="vertical"
  4. android:layout_width="fill_parent"
  5. android:layout_height="fill_parent"
  6. >
  7. <Button
  8. android:layout_width="wrap_content"
  9. android:layout_height="wrap_content"
  10. android:text="添加记录"
  11. android:id="@+id/insertbutton"
  12. />
  13. <LinearLayout
  14. android:orientation="horizontal"
  15. android:layout_width="fill_parent"
  16. android:layout_height="wrap_content">
  17. <TextView
  18. android:layout_width="80dip"
  19. android:layout_height="wrap_content"
  20. android:text="编号"
  21. />
  22. <TextView
  23. android:layout_width="100dip"
  24. android:layout_height="wrap_content"
  25. android:text="姓名"
  26. />
  27. <TextView
  28. android:layout_width="fill_parent"
  29. android:layout_height="wrap_content"
  30. android:text="存款"
  31. />
  32. </LinearLayout>
  33. <ListView
  34. android:layout_width="fill_parent"
  35. android:layout_height="fill_parent"
  36. android:id="@+id/listView"
  37. />
  38. </LinearLayout>




MainActivity.java(使用SimpleCursorAdapter方式获取数据,建议这个。)

[java] view plain copy print ?
 
  1. packagecom.nbchina.db;
  2. publicclassMainActivityextendsActivity{
  3. privatePersonServicepersonService;
  4. @Override
  5. publicvoidonCreate(BundlesavedInstanceState){
  6. super.onCreate(savedInstanceState);
  7. setContentView(R.layout.main);
  8. this.personService=newPersonService(this);
  9. ListViewlistView=(ListView)this.findViewById(R.id.listView);
  10. Cursorcursor=(Cursor)personService.getCursorScrollData(0,5);
  11. SimpleCursorAdapteradapter=newSimpleCursorAdapter(this,R.layout.item,cursor,
  12. newString[]{"_id","name","amount"},newint[]{R.id.id,R.id.name,R.id.amount});
  13. //记录集游标必须包括_id这个字段,否则会出错
  14. listView.setAdapter(adapter);
  15. listView.setOnItemClickListener(newOnItemClickListener(){
  16. @Override
  17. publicvoidonItemClick(AdapterView<?>parent,Viewview,intposition,longid){
  18. ListViewlView=(ListView)parent;
  19. Cursordata=(Cursor)lView.getItemAtPosition(position);
  20. intpersonid=data.getInt(data.getColumnIndex("_id"));
  21. Toast.makeText(MainActivity.this,personid+"",1).show();
  22. }
  23. });
  24. }
  25. }
  26. PersonService.java
  27. packagecom.nbchina.service;
  28. publicclassPersonService{
  29. privateDBOpenHelperdbOpenHelper;
  30. publicPersonService(Contextcontext){
  31. this.dbOpenHelper=newDBOpenHelper(context);
  32. }
  33. publicCursorgetCursorScrollData(Integeroffset,IntegermaxResult){
  34. //SimpleCursorAdaptercursor字段中必须有个_id。所以必须这么做
  35. SQLiteDatabasedb=dbOpenHelper.getReadableDatabase();
  36. returndb.rawQuery("selectpersonidas_id,name,amountfrompersonlimit?,?",
  37. newString[]{offset.toString(),maxResult.toString()});
  38. }
  39. }




MainActivity.java(使用SimpleAdapter方式获取数据,不建议)

[java] view plain copy print ?
 
  1. packagecom.nbchina.db;
  2. publicclassMainActivityextendsActivity{
  3. privatePersonServicepersonService;
  4. @Override
  5. publicvoidonCreate(BundlesavedInstanceState){
  6. super.onCreate(savedInstanceState);
  7. setContentView(R.layout.main);
  8. this.personService=newPersonService(this);
  9. ListViewlistView=(ListView)this.findViewById(R.id.listView);
  10. List<Person>persons=personService.getScrollData(0,5);
  11. List<HashMap<String,Object>>data=newArrayList<HashMap<String,Object>>();
  12. for(Personperson:persons){
  13. HashMap<String,Object>item=newHashMap<String,Object>();
  14. item.put("id",person.getId());
  15. item.put("name",person.getName());
  16. item.put("amount",person.getAmount());
  17. data.add(item);
  18. }
  19. SimpleAdapteradapter=newSimpleAdapter(this,data,R.layout.item,
  20. newString[]{"id","name","amount"},newint[]{R.id.id,R.id.name,R.id.amount});
  21. listView.setAdapter(adapter);
  22. listView.setOnItemClickListener(newOnItemClickListener(){
  23. @Override
  24. publicvoidonItemClick(AdapterView<?>parent,Viewview,intposition,longid){
  25. ListViewlView=(ListView)parent;
  26. HashMap<String,Object>item=(HashMap<String,Object>)lView.getItemAtPosition(position);
  27. Toast.makeText(MainActivity.this,item.get("id").toString(),1).show();
  28. }
  29. });
  30. }
  31. }
  32. PersonService.java
  33. packagecom.nbchina.service;
  34. publicclassPersonService{
  35. privateDBOpenHelperdbOpenHelper;
  36. publicPersonService(Contextcontext){
  37. this.dbOpenHelper=newDBOpenHelper(context);
  38. }
  39. publicList<Person>getScrollData(Integeroffset,IntegermaxResult){
  40. List<Person>persons=newArrayList<Person>();
  41. SQLiteDatabasedb=dbOpenHelper.getReadableDatabase();
  42. Cursorcursor=db.rawQuery("select*frompersonlimit?,?",
  43. newString[]{offset.toString(),maxResult.toString()});
  44. while(cursor.moveToNext()){
  45. intpersonid=cursor.getInt(cursor.getColumnIndex("personid"));
  46. Stringname=cursor.getString(cursor.getColumnIndex("name"));
  47. intamount=cursor.getInt(cursor.getColumnIndex("amount"));
  48. Personperson=newPerson(personid,name);
  49. person.setAmount(amount);
  50. persons.add(person);
  51. }
  52. cursor.close();
  53. returnpersons;
  54. }
  55. }



ContentProvider对外共享数据


一、配置AndroidManifest.xml

[java] view plain copy print ?
 
  1. <?xmlversion="1.0"encoding="utf-8"?>
  2. <manifestxmlns:android="http://schemas.android.com/apk/res/android"
  3. package="com.nbchina.db"
  4. android:versionCode="1"
  5. android:versionName="1.0">
  6. <applicationandroid:icon="@drawable/icon"android:label="@string/app_name">
  7. <uses-libraryandroid:name="android.test.runner"/>
  8. <activityandroid:name=".MainActivity"
  9. android:label="@string/app_name">
  10. ……
  11. </activity>
  12. <!--".PersonProvider"其中点代表应用的包路径。配置内容提供者-->
  13. <providerandroid:name=".PersonProvider"android:authorities="com.nbchina.providers.personprovider"/>
  14. </application>
  15. <uses-sdkandroid:minSdkVersion="8"/>
  16. </manifest>



二、建立PersonProvider.java 继承ContentProvider


[java] view plain copy print ?
 
  1. packagecom.nbchina.db;
  2. publicclassPersonProviderextendsContentProvider{
  3. //主件必须放入应用的包或者子包下。本项目person对外共享数据
  4. privateDBOpenHelperdbOpenHelper;
  5. //UriMatcher.NO_MATCH代表用户传进来的uri和里面所有的都不匹配的话,则返回NO_MATCH-1.
  6. privatestaticfinalUriMatcherMATCHER=newUriMatcher(UriMatcher.NO_MATCH);
  7. privatestaticfinalintPERSONS=1;
  8. privatestaticfinalintPERSON=2;
  9. static{
  10. MATCHER.addURI("com.nbchina.providers.personprovider","person",PERSONS);
  11. MATCHER.addURI("com.nbchina.providers.personprovider","person/#",PERSON);
  12. }
  13. @Override
  14. publicbooleanonCreate(){
  15. //当内容提供者被实例化之后调用。生命周期只调用一次。
  16. this.dbOpenHelper=newDBOpenHelper(this.getContext());
  17. returnfalse;
  18. }
  19. @Override
  20. publicStringgetType(Uriuri){//返回当前所操作数据的类型
  21. switch(MATCHER.match(uri)){
  22. casePERSONS:
  23. return"vnd.android.cursor.dir/person";
  24. casePERSON:
  25. return"vnd.android.cursor.item/person";
  26. default:
  27. thrownewIllegalArgumentException("UnkwonUri:"+uri.toString());
  28. }
  29. /*该方法用于返回当前Url所代表数据的MIME类型。
  30. 如果操作的数据属于集合类型,那么MIME类型字符串应该以vnd.android.cursor.dir/开头,
  31. 要得到所有person记录的Uri为content://com.nbchina.provider.personprovider/person,
  32. 那么返回的MIME类型字符串应该为:“vnd.android.cursor.dir/person”。
  33. 如果要操作的数据属于非集合类型数据,那么MIME类型字符串应该以vnd.android.cursor.item/开头,
  34. 得到id为10的person记录,Uri为content://com.nbchina.provider.personprovider/person/10,
  35. 那么返回的MIME类型字符串应该为:“vnd.android.cursor.item/person”。*/
  36. }
  37. @Override
  38. publicUriinsert(Uriuri,ContentValuesvalues){
  39. SQLiteDatabasedb=dbOpenHelper.getWritableDatabase();
  40. switch(MATCHER.match(uri)){
  41. casePERSONS:
  42. //如用字符串作为主键,则返回的是记录行号。若用数字作为主键,则返回的是主键值
  43. longrowid=db.insert("person","personid",values);
  44. <spanstyle="background-color:rgb(102,51,51);"><spanstyle="color:#ffffff;">//返回Uri,构造新的uri,把新id附加进去
  45. //ContentUris类使用介绍
  46. //ContentUris类用于获取Uri路径后面的ID部分,它有两个比较实用的方法:
  47. //withAppendedId(uri,id)用于为路径加上ID部分:
  48. //Uriuri=Uri.parse("content://cn.itcast.provider.personprovider/person")
  49. //UriresultUri=ContentUris.withAppendedId(uri,10);
  50. //生成后的Uri为:content://cn.itcast.provider.personprovider/person/10
  51. //parseId(uri)方法用于从路径中获取ID部分:
  52. //Uriuri=Uri.parse("content://cn.itcast.provider.personprovider/person/10")
  53. //longpersonid=ContentUris.parseId(uri);//获取的结果为:10</span></span>
  54. UriinsertUri=ContentUris.withAppendedId(uri,rowid);
  55. <spanstyle="background-color:rgb(0,0,102);"><spanstyle="color:#ffffff;">this.getContext().getContentResolver().notifyChange(uri,null);//通知Other项目中监听</span></span>
  56. returninsertUri;
  57. default:
  58. thrownewIllegalArgumentException("UnkwonUri:"+uri.toString());
  59. }
  60. }
  61. ……其他操作代码见实例
  62. }




Other项目中

[java] view plain copy print ?
 
  1. packagecom.nbchina.other;
  2. publicclassAccessContentProviderTestextendsAndroidTestCase{
  3. privatestaticfinalStringTAG="AccessContentProviderTest";
  4. /**
  5. *往内容提供者添加数据
  6. *@throwsThrowable
  7. */
  8. publicvoidtestInsert()throwsThrowable{
  9. 当外部应用需要对ContentProvider中的数据进行添加、删除、修改和查询操作时,可以使用ContentResolver类来完成,要获取ContentResolver对象,可以使用Activity提供的getContentResolver()方法。
  10. ContentResolvercontentResolver=this.getContext().getContentResolver();
  11. UriinsertUri=Uri.parse("content://com.nbchina.providers.personprovider/person");
  12. ContentValuesvalues=newContentValues();
  13. values.put("name","zhangxiaoxiao");
  14. values.put("amount",90);
  15. Uriuri=contentResolver.insert(insertUri,values);
  16. Log.i(TAG,uri.toString());
  17. }
  18. …其他操作见实例代码
  19. }




监听ContentProvider数据的变化
一、注册监听ContentProvider,在other项目中建立如下文件


[java] view plain copy print ?
 
  1. packagecom.nbchina.other;
  2. publicclassOtherActivityextendsActivity{
  3. //注册监听ContentProvider
  4. privatestaticfinalStringTAG="OtherActivity";
  5. @Override
  6. publicvoidonCreate(BundlesavedInstanceState){
  7. super.onCreate(savedInstanceState);
  8. setContentView(R.layout.main);
  9. UriinsertUri=Uri.parse("content://com.nbchina.providers.personprovider/person");
  10. ContentResolvercontentResolver=this.getContentResolver();
  11. //对指定uri进行监听,如果该uri代表的数据发生变化,就会调用PersonObserver中的onChange()
  12. <spanstyle="color:#ffffff;background-color:rgb(51,0,153);">contentResolver.registerContentObserver(insertUri,true,newPersonObserver(newHandler()));</span>
  13. }
  14. privatefinalclassPersonObserverextendsContentObserver{
  15. publicPersonObserver(Handlerhandler){
  16. super(handler);
  17. }
  18. @Override
  19. publicvoidonChange(booleanselfChange){//一旦数据发生改变,则查询所有内容
  20. ContentResolvercontentResolver=getContentResolver();
  21. UriselectUri=Uri.parse("content://com.nbchina.providers.personprovider/person");
  22. Cursorcursor=contentResolver.query(selectUri,null,null,null,"personiddesc");
  23. while(cursor.moveToNext()){
  24. intid=cursor.getInt(cursor.getColumnIndex("personid"));
  25. Stringname=cursor.getString(cursor.getColumnIndex("name"));
  26. intamount=cursor.getInt(cursor.getColumnIndex("amount"));
  27. Log.i(TAG,"id="+id+",name="+name+",amount="+amount);
  28. }
  29. }
  30. }
  31. }



PersonProvider 的insert方法内加入如下代码

this.getContext().getContentResolver().notifyChange(uri, null);//通知




通信录中的联系人操作

手机内项目都通过内容提供者进行操作。


联系人内容提供者
D:\android-sdk-windows\platforms\android-8\sources\ContactsProvider\src\com\android\providers\contacts\ContactsProvider2.java
呼叫记录内容提供者
D:\android-sdk-windows\platforms\android-8\sources\ContactsProvider\src\com\android\providers\contacts\CallLogProvider.java
短信内容提供者
D:\android-sdk-windows\platforms\android-8\sources\TelephonyProvider\src\com\android\providers\telephony\SmsProvider.java
彩信内容提供者
D:\android-sdk-windows\platforms\android-8\sources\TelephonyProvider\src\com\android\providers\telephony\MmsProvider.java
电话内容提供者
D:\android-sdk-windows\platforms\android-8\sources\TelephonyProvider\src\com\android\providers\telephony\ TelephonyProvider.java


建立 Content项目


AndroidManifest.xml内加入权限


[java] view plain copy print ?
 
  1. <?xmlversion="1.0"encoding="utf-8"?>
  2. <manifestxmlns:android="http://schemas.android.com/apk/res/android"
  3. package="com.nbchina.contact"
  4. android:versionCode="1"
  5. android:versionName="1.0">
  6. <applicationandroid:icon="@drawable/icon"android:label="@string/app_name">
  7. <uses-libraryandroid:name="android.test.runner"/>
  8. </application>
  9. <uses-permissionandroid:name="android.permission.READ_CONTACTS"/>
  10. <uses-permissionandroid:name="android.permission.WRITE_CONTACTS"/>
  11. <instrumentationandroid:name="android.test.InstrumentationTestRunner"
  12. android:targetPackage="com.nbchina.contact"android:label="TestsforMyApp"/>
  13. </manifest>





手机内容提供者操作代码如下

[java] view plain copy print ?
 
  1. ContactTest.java
  2. packagecom.nbchina.contact;
  3. publicclassContactTestextendsAndroidTestCase{
  4. privatestaticfinalStringTAG="ContactTest";
  5. publicvoidtestGetAllContact()throwsThrowable{
  6. //content://com.android.contacts/contacts
  7. Uriuri=ContactsContract.Contacts.CONTENT_URI;
  8. //访问内容提供者
  9. ContentResolvercontentResolver=this.getContext().getContentResolver();
  10. //查询所有数据
  11. //contentResolver.query(uri,projection,selection,selectionArgs,sortOrder)
  12. Cursorcursor=contentResolver.query(uri,null,null,null,null);
  13. while(cursor.moveToNext()){
  14. StringBuildersb=newStringBuilder();
  15. StringcontactId=cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
  16. Stringname=cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
  17. sb.append("contactId=").append(contactId).append(",name=").append(name);
  18. Cursorphones=contentResolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
  19. null,
  20. ContactsContract.CommonDataKinds.Phone.CONTACT_ID+"="+contactId,
  21. null,null);
  22. while(phones.moveToNext()){
  23. StringphoneNumber=phones.getString(phones.getColumnIndex(
  24. ContactsContract.CommonDataKinds.Phone.NUMBER));
  25. sb.append(",phone=").append(phoneNumber);
  26. }
  27. phones.close();
  28. Cursoremails=contentResolver.query(ContactsContract.CommonDataKinds.Email.CONTENT_URI,
  29. null,
  30. ContactsContract.CommonDataKinds.Email.CONTACT_ID+"="+contactId,
  31. null,null);
  32. while(emails.moveToNext()){
  33. StringemailAddress=emails.getString(emails.getColumnIndex(
  34. ContactsContract.CommonDataKinds.Email.DATA));
  35. sb.append(",emailAddress=").append(emailAddress);
  36. }
  37. emails.close();
  38. Log.i(TAG,sb.toString());
  39. }
  40. cursor.close();
  41. }
  42. /**
  43. *首先向RawContacts.CONTENT_URI执行一个空值插入,目的是获取系统返回的rawContactId
  44. *这时后面插入data表的依据,只有执行空值插入,才能使插入的联系人在通讯录里面可见
  45. */
  46. publicvoidtestInsert(){
  47. ContentValuesvalues=newContentValues();
  48. //首先向RawContacts.CONTENT_URI执行一个空值插入,目的是获取系统返回的rawContactId
  49. UrirawContactUri=this.getContext().getContentResolver().insert(RawContacts.CONTENT_URI,values);
  50. longrawContactId=ContentUris.parseId(rawContactUri);
  51. //往data表入姓名数据
  52. values.clear();
  53. values.put(Data.RAW_CONTACT_ID,rawContactId);
  54. values.put(Data.MIMETYPE,StructuredName.CONTENT_ITEM_TYPE);//内容类型
  55. values.put(StructuredName.GIVEN_NAME,"李天山");
  56. this.getContext().getContentResolver().insert(android.provider.ContactsContract.Data.CONTENT_URI,values);
  57. //往data表入电话数据
  58. values.clear();
  59. values.put(Data.RAW_CONTACT_ID,rawContactId);
  60. values.put(Data.MIMETYPE,Phone.CONTENT_ITEM_TYPE);
  61. values.put(Phone.NUMBER,"13921009789");
  62. values.put(Phone.TYPE,Phone.TYPE_MOBILE);
  63. this.getContext().getContentResolver().insert(android.provider.ContactsContract.Data.CONTENT_URI,values);
  64. //往data表入Email数据
  65. values.clear();
  66. values.put(Data.RAW_CONTACT_ID,rawContactId);
  67. values.put(Data.MIMETYPE,Email.CONTENT_ITEM_TYPE);
  68. values.put(Email.DATA,"liming@itcast.cn");
  69. values.put(Email.TYPE,Email.TYPE_WORK);
  70. this.getContext().getContentResolver().insert(android.provider.ContactsContract.Data.CONTENT_URI,values);
  71. }
  72. //批量添加,处于同一个事务中.一般添加最好使用此方式。删除修改等自己研究。
  73. publicvoidtestSave()throwsThrowable{
  74. //文档位置:reference\android\provider\ContactsContract.RawContacts.html
  75. ArrayList<ContentProviderOperation>ops=newArrayList<ContentProviderOperation>();
  76. intrawContactInsertIndex=ops.size();
  77. ops.add(ContentProviderOperation.newInsert(RawContacts.CONTENT_URI)
  78. .withValue(RawContacts.ACCOUNT_TYPE,null)
  79. .withValue(RawContacts.ACCOUNT_NAME,null)
  80. .build());
  81. //文档位置:reference\android\provider\ContactsContract.Data.html
  82. ops.add(ContentProviderOperation.newInsert(android.provider.ContactsContract.Data.CONTENT_URI)
  83. .withValueBackReference(Data.RAW_CONTACT_ID,rawContactInsertIndex)
  84. .withValue(Data.MIMETYPE,StructuredName.CONTENT_ITEM_TYPE)
  85. .withValue(StructuredName.GIVEN_NAME,"赵薇")
  86. .build());
  87. ops.add(ContentProviderOperation.newInsert(android.provider.ContactsContract.Data.CONTENT_URI)
  88. .withValueBackReference(Data.RAW_CONTACT_ID,rawContactInsertIndex)
  89. .withValue(Data.MIMETYPE,Phone.CONTENT_ITEM_TYPE)
  90. .withValue(Phone.NUMBER,"13671323809")
  91. .withValue(Phone.TYPE,Phone.TYPE_MOBILE)
  92. .withValue(Phone.LABEL,"手机号")
  93. .build());
  94. ops.add(ContentProviderOperation.newInsert(android.provider.ContactsContract.Data.CONTENT_URI)
  95. .withValueBackReference(Data.RAW_CONTACT_ID,rawContactInsertIndex)
  96. .withValue(Data.MIMETYPE,Email.CONTENT_ITEM_TYPE)
  97. .withValue(Email.DATA,"liming@nbchina.cn")
  98. .withValue(Email.TYPE,Email.TYPE_WORK)
  99. .build());
  100. ContentProviderResult[]results=this.getContext().getContentResolver()
  101. .applyBatch(ContactsContract.AUTHORITY,ops);
  102. for(ContentProviderResultresult:results){
  103. Log.i(TAG,result.uri.toString());
  104. }
  105. }
  106. }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值