Android中使用ContentProvider管理系统资源的实例
Android中使用ContentProvider管理系统资源的实例
发布时间:2016-12-28 来源:查字典编辑
摘要:ContentProvider管理联系人的实例:packagecom.android.xiong.getsystemcontentprovi...

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>

<"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>

<"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>

<"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>

推荐文章
猜你喜欢
附近的人在看
推荐阅读
拓展阅读
相关阅读
网友关注
最新安卓软件开发学习
热门安卓软件开发学习
编程开发子分类