欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

Android中使用ContentProvider管理系统资源的实例

程序员文章站 2024-03-01 18:54:16
contentprovider管理联系人的实例: package com.android.xiong.getsystemcontentprovidertest...

contentprovider管理联系人的实例:

package com.android.xiong.getsystemcontentprovidertest; 
 
import java.util.arraylist; 
 
import android.app.activity; 
import android.app.alertdialog; 
import android.content.contenturis; 
import android.content.contentvalues; 
import android.database.cursor; 
import android.net.uri; 
import android.os.bundle; 
import android.provider.contactscontract; 
import android.provider.contactscontract.commondatakinds.email; 
import android.provider.contactscontract.commondatakinds.phone; 
import android.provider.contactscontract.commondatakinds.structuredname; 
import android.provider.contactscontract.data; 
import android.provider.contactscontract.rawcontacts; 
import android.view.gravity; 
import android.view.menu; 
import android.view.view; 
import android.view.view.onclicklistener; 
import android.view.viewgroup; 
import android.widget.abslistview; 
import android.widget.abslistview.layoutparams; 
import android.widget.baseexpandablelistadapter; 
import android.widget.button; 
import android.widget.edittext; 
import android.widget.expandablelistadapter; 
import android.widget.expandablelistview; 
import android.widget.textview; 
import android.widget.toast; 
 
public class mainactivity extends activity { 
 
  private button bt1, bt2; 
  private expandablelistview exp1; 
 
  @override 
  protected void oncreate(bundle savedinstancestate) { 
    super.oncreate(savedinstancestate); 
    setcontentview(r.layout.activity_main); 
    bt1 = (button) findviewbyid(r.id.bt1); 
    bt1.setonclicklistener(new lookpresonclick()); 
    bt2 = (button) findviewbyid(r.id.bt2); 
    bt2.setonclicklistener(new addpersonclick()); 
 
  } 
 
  class addpersonclick implements onclicklistener { 
 
    @override 
    public void onclick(view v) { 
      // 获取程序界面中的桑文本框 
      string name = ((edittext) findviewbyid(r.id.ed1)).gettext() 
          .tostring(); 
      string phone = ((edittext) findviewbyid(r.id.ed2)).gettext() 
          .tostring(); 
      string email = ((edittext) findviewbyid(r.id.ed3)).gettext() 
          .tostring(); 
      // 创建一个空的contentvalue 
      contentvalues values = new contentvalues(); 
      // 向rawcontacts.contnt_uri执行一个空值插入 
      // 目的是获取系统返回的rawcontactid 
      uri rawcontactsuri = getcontentresolver().insert( 
          rawcontacts.content_uri, values); 
      long rawcontactid = contenturis.parseid(rawcontactsuri); 
      values.clear(); 
      values.put(data.raw_contact_id, rawcontactid); 
      // 设置内容类型 
      values.put(data.mimetype, structuredname.content_item_type); 
      // 设置联系人名字 
      values.put(structuredname.given_name, name); 
      // 向联系人uri添加联系人名字 
      getcontentresolver().insert( 
          android.provider.contactscontract.data.content_uri, values); 
      values.clear(); 
      values.put(data.raw_contact_id, rawcontactid); 
      values.put(data.mimetype, phone.content_item_type); 
      // 设置联系人的电话 
      values.put(phone.number, phone); 
      // 设置电话类型 
      values.put(phone.type, phone.type_mobile); 
      // 向联系人电话uri添加电话号码 
      getcontentresolver().insert( 
          android.provider.contactscontract.data.content_uri, values); 
      values.clear(); 
      values.put(data.raw_contact_id, rawcontactid); 
      values.put(data.mimetype, email.content_item_type); 
      // 设置联系人的email地址 
      values.put(email.data, email); 
      // 设置email的类型 
      values.put(email.type, email.type_work); 
      getcontentresolver().insert( 
          android.provider.contactscontract.data.content_uri, values); 
      toast.maketext(mainactivity.this, "添加联系人信息成功", toast.length_long) 
          .show(); 
 
    } 
 
  } 
 
  class lookpresonclick implements onclicklistener { 
 
    @override 
    public void onclick(view v) { 
      // 定义两个list来封装系统联系人信息,指定联系人的电话,email等详情 
      final arraylist<string> names = new arraylist<string>(); 
      final arraylist<arraylist<string>> details = new arraylist<arraylist<string>>(); 
      // 使用contentresolver查找联系人数据 
      cursor cursor = getcontentresolver().query( 
          contactscontract.contacts.content_uri, null, null, null, 
          null); 
      // 遍历结果 获取系统所有联系人信息 
      while (cursor.movetonext()) { 
        // 获取联系人id 
        string contactid = cursor.getstring(cursor 
            .getcolumnindex(contactscontract.contacts._id)); 
        // 获取联系人的名字 
        string name = cursor 
            .getstring(cursor 
                .getcolumnindex(contactscontract.contacts.display_name)); 
        names.add(name); 
        // 使用contentresolver查找联系人的电话号码 
        cursor phones = getcontentresolver().query( 
            contactscontract.commondatakinds.phone.content_uri, 
            null, 
            contactscontract.commondatakinds.phone.contact_id 
                + "= ?", new string[] { contactid }, null); 
        arraylist<string> detail = new arraylist<string>(); 
        // 遍历查询结果,获取该联系人的多个电话 
        while (phones.movetonext()) { 
          // 获取查询的结果中的电话号码列 
          string phonenumber = phones 
              .getstring(phones 
                  .getcolumnindex(contactscontract.commondatakinds.phone.number)); 
          detail.add("电话号码是:" + phonenumber); 
        } 
        phones.close(); 
        // 使用contentresolver查找联系人的e-mail地址 
        cursor emails = getcontentresolver().query( 
            contactscontract.commondatakinds.email.content_uri, 
            null, 
            contactscontract.commondatakinds.email.contact_id 
                + " =?", new string[] { contactid }, null); 
        // 遍历查询结果,获取该联系人的多个email地址 
        while (emails.movetonext()) { 
          // 获取查询的结果中email地址中列的数据 
          string emailaddress = emails 
              .getstring(emails 
                  .getcolumnindex(contactscontract.commondatakinds.email.data)); 
          detail.add("email是:" + emailaddress); 
        } 
        emails.close(); 
        details.add(detail); 
 
      } 
      cursor.close(); 
 
      // 加载result.xml界面布局代表的视图 
      view resultdialog = getlayoutinflater().inflate(r.layout.result, 
          null); 
      exp1 = (expandablelistview) resultdialog.findviewbyid(r.id.exp1); 
      // 创建一个expandablelistadapter对象 
      expandablelistadapter adapter = new baseexpandablelistadapter() { 
 
        @override 
        public boolean ischildselectable(int groupposition, 
            int childposition) { 
          // todo auto-generated method stub 
          return true; 
        } 
 
        @override 
        public boolean hasstableids() { 
          // todo auto-generated method stub 
          return true; 
        } 
 
        @override 
        public view getgroupview(int groupposition, boolean isexpanded, 
            view convertview, viewgroup parent) { 
          textview text = gettextveiw(); 
          text.settext(getgroup(groupposition).tostring()); 
          return text; 
        } 
 
        @override 
        public long getgroupid(int groupposition) { 
          // todo auto-generated method stub 
          return groupposition; 
        } 
 
        @override 
        public int getgroupcount() { 
          // todo auto-generated method stub 
          return names.size(); 
        } 
 
        @override 
        public object getgroup(int groupposition) { 
          // todo auto-generated method stub 
          return names.get(groupposition); 
        } 
 
        @override 
        public int getchildrencount(int groupposition) { 
          // todo auto-generated method stub 
          return details.get(groupposition).size(); 
        } 
 
        private textview gettextveiw() { 
          abslistview.layoutparams lp = new layoutparams( 
              viewgroup.layoutparams.match_parent, 64); 
          textview textview = new textview(mainactivity.this); 
          textview.setlayoutparams(lp); 
          textview.setgravity(gravity.center_vertical | gravity.left); 
          textview.setpadding(36, 0, 0, 0); 
          textview.settextsize(20); 
          return textview; 
        } 
 
        @override 
        public view getchildview(int groupposition, int childposition, 
            boolean islastchild, view convertview, viewgroup parent) { 
          textview textview = gettextveiw(); 
          textview.settext(getchild(groupposition, childposition) 
              .tostring()); 
 
          return textview; 
        } 
 
        @override 
        public long getchildid(int groupposition, int childposition) { 
          // todo auto-generated method stub 
          return childposition; 
        } 
 
        @override 
        public object getchild(int groupposition, int childposition) { 
          return details.get(groupposition).get(childposition); 
        } 
      }; 
      exp1.setadapter(adapter); 
      // 使用对话框来显示查询结果 
      new alertdialog.builder(mainactivity.this).setview(resultdialog) 
          .setpositivebutton("确定", null).show(); 
    } 
 
  } 
 
  @override 
  public boolean oncreateoptionsmenu(menu menu) { 
    // inflate the menu; this adds items to the action bar if it is present. 
    getmenuinflater().inflate(r.menu.main, menu); 
    return true; 
  } 
 
} 
<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" 
  tools:context=".mainactivity" > 
 
    <edittext  
    android:id="@+id/ed1" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:hint="输入联系人姓名"/> 
    <edittext  
      android:id="@+id/ed2" 
      android:layout_width="match_parent" 
      android:layout_height="wrap_content" 
      android:hint="输入联系人电话"/> 
    <edittext  
      android:id="@+id/ed3" 
      android:layout_width="match_parent" 
      android:layout_height="wrap_content" 
      android:hint="输入联系人email"/> 
    <button  
      android:id="@+id/bt2" 
      android:layout_width="match_parent" 
      android:layout_height="wrap_content" 
      android:text="添加联系人信息"/> 
  <button 
    android:id="@+id/bt1" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:text="查看联系人" /> 
 
 
</linearlayout> 

<?xml version="1.0" encoding="utf-8"?> 
<linearlayout xmlns:android="http://schemas.android.com/apk/res/android" 
  android:layout_width="match_parent" 
  android:layout_height="match_parent" 
  android:orientation="vertical" > 
   
 
  <expandablelistview 
    android:id="@+id/exp1" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" > 
  </expandablelistview> 
</linearlayout> 

使用contentprovider管理多媒体内容
android为多媒体提供的uri:
1、mediastore.audio.mdia.external_content_uri:存储在外部设备上的音频文件
2、mediastore.audio.mdia.internal_content_uri:存储在手机内部上的音频文件
3、mediastore.images.mdia.external_content_uri:存储在外部设备上的图片文件
4、mediastore.images.mdia.internal_content_uri:存储在内部设备上的图片文件
5、mediastore.video.mdia.external_content_uri:存储在外部设备上的音频文件
6、mediastore.video.mdia.internal_content_uri:存储在内部设备上的音频文件
实例:

package com.example.mediaprovidertest; 
 
import java.io.ioexception; 
import java.io.outputstream; 
import java.util.arraylist; 
import java.util.hashmap; 
import java.util.list; 
import java.util.map; 
 
import android.app.activity; 
import android.app.alertdialog; 
import android.content.contentvalues; 
import android.database.cursor; 
import android.graphics.bitmap; 
import android.graphics.bitmapfactory; 
import android.net.uri; 
import android.os.bundle; 
import android.provider.mediastore.images.media; 
import android.view.menu; 
import android.view.view; 
import android.view.view.onclicklistener; 
import android.widget.adapterview; 
import android.widget.adapterview.onitemclicklistener; 
import android.widget.button; 
import android.widget.imageview; 
import android.widget.listview; 
import android.widget.simpleadapter; 
import android.widget.textview; 
 
public class mainactivity extends activity { 
 
  private button bt1, bt2; 
  private listview list1; 
 
  arraylist<string> names = new arraylist<string>(); 
  arraylist<string> descs = new arraylist<string>(); 
  arraylist<string> filenames = new arraylist<string>(); 
 
  @override 
  protected void oncreate(bundle savedinstancestate) { 
    super.oncreate(savedinstancestate); 
    setcontentview(r.layout.activity_main); 
    bt1 = (button) findviewbyid(r.id.bt1); 
    bt2 = (button) findviewbyid(r.id.bt2); 
    list1 = (listview) findviewbyid(r.id.list); 
 
    bt1.setonclicklistener(new onclicklistener() { 
 
      @override 
      public void onclick(view v) { 
        // 清空names、desc、filename集合里原有的数据 
        names.clear(); 
        descs.clear(); 
        filenames.clear(); 
        // 通过contentresolver查询所有图片信息 
        cursor curos = getcontentresolver().query( 
            media.external_content_uri, null, null, null, null); 
        while (curos.movetonext()) { 
          // 获取图片显示的名字 
          string name = curos.getstring(curos 
              .getcolumnindex(media.display_name)); 
          // 获取图片的详细信息、 
          string desc = curos.getstring(curos 
              .getcolumnindex(media.description)); 
          // 将图片名保存的位置数据 
          byte[] data = curos.getblob(curos 
              .getcolumnindex(media.data)); 
          // 将图片名添加到names集合中 
          names.add(name); 
          // 将图片描述添加到desc集合中 
          descs.add(desc); 
          // 将图片保存路径添加到filenames集合中 
          filenames.add(new string(data, 0, data.length - 1)); 
        } 
        // 创建一个list集合的元素是map 
        list<map<string, object>> listitems = new arraylist<map<string, object>>(); 
        // 将names、descs两个集合对象的数据转换到map集合 
        for (int i = 0; i < names.size(); i++) { 
          map<string, object> listitem = new hashmap<string, object>(); 
          listitem.put("name", names.get(i)); 
          listitem.put("desc", descs.get(i)); 
          listitems.add(listitem); 
        } 
        simpleadapter simple = new simpleadapter(mainactivity.this, 
            listitems, r.layout.items, new string[] { "name", 
                "desc" }, new int[] { r.id.txt1, r.id.txt2 }); 
        list1.setadapter(simple); 
 
      } 
    }); 
    list1.setonitemclicklistener(new onitemclicklistener() { 
 
      @override 
      public void onitemclick(adapterview<?> arg0, view arg1, int arg2, 
          long arg3) { 
        // 加载view.xml界面布局代表视图 
        view view = getlayoutinflater().inflate(r.layout.view, null); 
        // 获取viewdialog中imageview组件 
        imageview image1 = (imageview) view.findviewbyid(r.id.image1); 
        // 设置image显示指定的图片 
        image1.setimagebitmap(bitmapfactory.decodefile(filenames 
            .get(arg2))); 
        // 使用对话框显示用户单击的图片 
        new alertdialog.builder(mainactivity.this).setview(view) 
            .setpositivebutton("确定", null).show(); 
 
      } 
    }); 
    bt2.setonclicklistener(new onclicklistener() { 
 
      @override 
      public void onclick(view v) { 
        // 创建contentvalues对象,准备插入数据 
        contentvalues values = new contentvalues(); 
        values.put(media.display_name, "jinta"); 
        values.put(media.description, "金塔"); 
        values.put(media.mime_type, "image/jpeg"); 
        // 插入数据对应的uri 
        uri uri = getcontentresolver().insert( 
            media.external_content_uri, values); 
        // 加载应用程序下的jinta图片 
        bitmap bitmap = bitmapfactory.decoderesource( 
            mainactivity.this.getresources(), r.drawable.jinta); 
        outputstream os = null; 
        try { 
          // 获取刚插入的数据的uri对应的输出流 
          os = getcontentresolver().openoutputstream(uri); 
          // 将bitmap图片保存到uri对应的数据节点中 
          bitmap.compress(bitmap.compressformat.jpeg, 100, os); 
          os.close(); 
        } catch (ioexception io) { 
          io.printstacktrace(); 
        } 
      } 
    }); 
  } 
 
  @override 
  public boolean oncreateoptionsmenu(menu menu) { 
    // inflate the menu; this adds items to the action bar if it is present. 
    getmenuinflater().inflate(r.menu.main, menu); 
    return true; 
  } 
 
} 
<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" 
  tools:context=".mainactivity" > 
   
  <button  
    android:id="@+id/bt1" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:text="查看图片"/> 
  <button  
    android:id="@+id/bt2" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:text="添加图片"/> 
  <listview  
    android:id="@+id/list" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content"></listview> 
 
 
 
</linearlayout> 


<?xml version="1.0" encoding="utf-8"?> 
<linearlayout xmlns:android="http://schemas.android.com/apk/res/android" 
  android:layout_width="match_parent" 
  android:layout_height="match_parent" 
  android:orientation="vertical" > 
  <textview  
    android:id="@+id/txt1" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content"/> 
  <textview  
    android:id="@+id/txt2" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content"/> 
   
 
</linearlayout> 
<?xml version="1.0" encoding="utf-8"?> 
<linearlayout xmlns:android="http://schemas.android.com/apk/res/android" 
  android:layout_width="match_parent" 
  android:layout_height="match_parent" 
  android:orientation="vertical" > 
 
    <imageview 
      android:id="@+id/image1" 
      android:layout_width="match_parent" 
      android:layout_height="match_parent" /> 
 
</linearlayout>