Android 存储知识总结

本文详细介绍了Android应用中常见的四种数据存储方式:文件存储、SharePreferences存储、SQLite数据库存储及ContentProvider存储。针对每种存储方式的特点和应用场景进行了深入解析,并提供了具体的实现代码示例。

1:文件存储-----存储简单数据(openFileOutput-FileOutputStream和openFileInput-FileInputStream),txt和

具体实例:

public class MainActivity extends AppCompatActivity {
    private static final String TAG = "aileinfo";
    private String mDataPath = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator;
    private String mEngFilePath = mDataPath + File.separator + "tessdata" + File.separator + "eng.traineddata";

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        txtFileOp();
        imgVideoFileOp();
         copyEngFile();
         saveBitmap(bitmap, bos);
    }

	//txt操作
    private void txtFileOp() {
        File aileFile = new File(Environment.getExternalStorageDirectory() + "/00000" + "/aile.txt");
        if (!aileFile.getParentFile().exists()) {
            aileFile.getParentFile().mkdir();
        }
        try {
            FileOutputStream fos = new FileOutputStream(aileFile);
            fos.write("we are good kids!".getBytes());

            FileInputStream fis = new FileInputStream(aileFile);
            int len = -1;
            byte[] buf = new byte[2048];
            StringBuilder sb = new StringBuilder();
            while ((len = fis.read(buf)) != -1) {
                sb.append(new String(buf, 0, len));
                Log.i(TAG, sb.toString());
            }
            fis.close();
            fos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
	 //图片和视频复制
    private void imgVideoFileOp() {
        File downloadDirFile = new File(Environment.getExternalStorageDirectory() + "/000" + "/12.mp4");
        File destDirFile = new File(Environment.getExternalStorageDirectory() + "/111" + "/11.mp4");
        if (!destDirFile.getParentFile().exists()) {
            destDirFile.getParentFile().mkdir();
        }
        try {
            FileInputStream fis = new FileInputStream(downloadDirFile);
            FileOutputStream fos = new FileOutputStream(destDirFile);
            int len = -1;
            byte[] buf = new byte[2048];
            while ((len = fis.read(buf)) != -1) {
                fos.write(buf, 0, len);
            }
            fis.close();
            fos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

//将assets目录语言包复制到内置存储卡中
private void copyEngFile() {
        try {
            File mFile = new File(mEngFilePath);
            if (mFile.exists()) {
                mFile.delete();
            }
            if (!mFile.exists()) {
                File p = new File(mFile.getParent());
                if (!p.exists()) {
                    p.mkdirs();
                }
                try {
                    mFile.createNewFile();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            OutputStream os = new FileOutputStream(mEngFilePath);
            InputStream is = this.getAssets().open("eng.traineddata");
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = is.read(buffer)) != -1) {
                os.write(buffer, 0, len);
            }
            os.flush();
            os.close();
            is.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

//保存图片到本地并更新图库
public void saveBitmap(Bitmap bitmap, ByteArrayOutputStream bos) {
        try {
            File fileImage = new File(getFantasyBitmap(getApplicationContext()));
            if (!fileImage.exists()) {
                fileImage.createNewFile();
            }
            FileOutputStream out = new FileOutputStream(fileImage);
            if (out != null) {
                //等比例缩放
                byte[] bipByte = bos.toByteArray();
                BitmapFactory.Options opts = new BitmapFactory.Options();
                opts.inSampleSize = 2;
                bitmap = BitmapFactory.decodeByteArray(bipByte, 0, bipByte.length, opts);
                //图片保存本地
                bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
                out.flush();
                out.close();
                Intent media = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                Uri contentUri = Uri.fromFile(fileImage);
                media.setData(contentUri);
                sendBroadcast(media);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

// 内部存储:也就是DDMS data文件夹(shared_prefs,databases,files,cache四个目录)

File file = getFilesDir();
	File file = getCacheDir();
	File file = getDir("music", MODE_PRIVATE);
	File file = getDatabasePath("user.db");

// 向本地存储,放在/data/data/files/abc.txt

try {
		//写入数据
		FileOutputStream out = openFileOutput("abc.txt", MODE_PRIVATE);
		out.write("this is my test".getBytes());
		out.flush();
		out.close();
		//先读取数据然后再一个个字节写入数据
		FileInputStream is = openFileInput("abc.txt");
		ByteArrayOutputStream os = new ByteArrayOutputStream();
		int len = -1;
		byte[] bytes = new byte[256];
		while ((len = is.read(bytes)) != -1) {
		os.write(bytes, 0, len);
		os.flush();
		}
		os.close();
		Log.i("info", "info:" + new String(os.toByteArray()));
		} catch (FileNotFoundException e) {
		e.printStackTrace();
		} catch (IOException e) {
		e.printStackTrace();
		}

// 外部存储,也就是SDcard存储

File file = getExternalCacheDir();//SDcard缓存目录
	File file = getExternalFilesDir(Environment.DIRECTORY_MOVIES);//SDcard文件目录

// Environment方法

File file = Environment.getDataDirectory();
	File file = Environment.getDownloadCacheDirectory();
	File file = Environment.getRootDirectory();

//SDcard文件写入和读取数据

//写入
	if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
	File sdCardDir=Environment.getExternalStorageDirectory;
	File saveFile=new File(sdCardDir,"wandal.txt");
	try {
	FileOutputStream fos=new FileOutputStream(saveFile);
	fos.write("women dou shi hao haizi !".getBytes());
	fos.close();
	}catch (Exception e){
	e.printStackTrace();
	}
	}
	//读取
	try {
	FileInputStream fis=new FileInputStream(saveFile);
	int len=0;
	byte[] buf=new byte[1024];
	StringBuilder sb=new StringBuilder();
	while (len=fis.read(buf)!=-1){
	sb.append(new String(buf,0,len));
	}
	fis.close();
	}catch (Exception e){
	e.printStackTrace();
	}

// 创建并获取/mnt/sdcard/DCIM

String state = Environment.getExternalStorageState();
		Log.i("info", "state:" + state);
		if (Environment.MEDIA_MOUNTED.equals(state)) {File file = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
		Log.i("info", "getExternalStoragePublicDirectory() : "+ file.getAbsolutePath());
		}

// 获取根目录下的所有文件

	File root = new File("/");
		String[] files = root.list();
		for (String name : files) {
			Log.i("info", name);
		}

//如果数据库文件不存在,目的是将开发包assets中的数据库复制到本地数据目录中的dababases文件中.

File file = getDatabasePath("user.db");
		if (!file.exists()) {
			try {
				if (!file.getParentFile().exists()) {
					file.getParentFile().mkdirs();
				}
				// 复制原生资源目录中的数据库 到数据库目录
				AssetManager manager = getAssets();
				InputStream in = manager.open("user.db");
				FileOutputStream out = new FileOutputStream(file);
				int len = -1;
				byte[] bytes = new byte[1024];
				while ((len = in.read(bytes)) != -1) {
					out.write(bytes, 0, len);
					out.flush();
				}
				out.close();
				in.close();
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

2:SharePreferences存储(常用场景为登陆界面和单选框选中设置)-----实质为data/shared_prefs目录下xml文件,简单的配置信息
可以通过getSharedPreferences(“userpassword”,MODE_PRIVATE)创建名为userpassword的xml文件
创建实例:

private SharedPreferences pref;
		pref = PreferenceManager.getDefaultSharedPreferences(this);

存储数据:

String name = etName.getText().toString();
		String pass = etPass.getText().toString();
		if ("admin".equals(name) &&"123456".equals(pass)) {
				if (chkSaveName.isChecked()) {
				//实质就是xml键值对,存放语法
					pref.edit().putString("name", name).commit();
				} else {
					pref.edit().remove(name).commit();
				}
				Intent intent = new Intent(this, MainActivity.class);
				startActivity(intent);
				finish();
			}else{
				etPass.setText("");
		}

获取数据:

String name = pref.getString("name", null);
		if (name != null) {
			etName.setText(name);
			chkSaveName.setChecked(true);
		} else {
			chkSaveName.setChecked(false);
		}

3:SQLite数据库存储,系统自带轻量级嵌入式数据库,可存储复杂数据,和ContentProvider区别就是直接操作数据库
//继承SQLiteOpenHelper创建表格

public class DBOpenHelper extends SQLiteOpenHelper {
	public DBOpenHelper(Context context, String dbName) {
		super(context, dbName, null, 1);
	}
	public void onCreate(SQLiteDatabase db) {
		Log.i("info", "创建表结构");
		db.execSQL("create table if not exists usertbl("
				+ "_id integer primary key autoincrement,"
				+ "name text not null," + "password text not null" + ")");
		db.execSQL("insert into usertbl(name,password) values('admin','123456')");
		db.execSQL("insert into usertbl(name,password) values('kitty','888888')");

		db.execSQL("create table if not exists stutbl("
				+ "_id integer primary key autoincrement,"
				+ "name text not null," + "sex text not null," + "age integer"
				+ ")");
	}
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
	//用于软件升级时的数据库表和数据更新
	if (oldVersion==1 && new newVersion==2){
		db.execSQL("alter table usertbl add softversion VARCHAR(15)");
	}
	}
	}

//SQLiteOpenHelper增删改查操作数据

private DBOpenHelper helper;
helper = new DBOpenHelper(context, "stu.db");
//增
public long addStudent(Student stu) {
		long rowId = -1;
		SQLiteDatabase db = helper.getWritableDatabase();
		ContentValues values = new ContentValues();
		values.put("name", stu.getName());
		values.put("sex", stu.getSex());
		values.put("age", stu.getAge());
		long rowId = db.insert("stutbl", null, values);
		db.close();
		return rowId;
	}
//改
	public int updateStudent(Student stu) {
		int count = 0;
		SQLiteDatabase db = helper.getWritableDatabase();
		ContentValues values = new ContentValues();
		values.put("name", stu.getName());
		values.put("sex", stu.getSex());
		values.put("age", stu.getAge());
		count = db.update("stutbl", values, "_id=" + stu.getId(), null);
		return count;
	}
//删
	public int removeStudent(int id) {
		int count = 0;
		SQLiteDatabase db = helper.getWritableDatabase();
		count = db.delete("stutbl", "_id=" + id, null);
		return count;
	}
//查
	public ArrayList<Student> getStudents() {
		ArrayList<Student> students = null;
		SQLiteDatabase db = helper.getReadableDatabase();
		Cursor c = db.rawQuery("select * from stutbl", null);
		if (c != null) {
			students = new ArrayList<Student>();
			while (c.moveToNext()) {
				Student stu = new Student();
				stu.setId(c.getInt(c.getColumnIndex("_id")));
				stu.setName(c.getString(c.getColumnIndex("name")));
				stu.setSex(c.getString(c.getColumnIndex("sex")));
				stu.setAge(c.getInt(c.getColumnIndex("age")));
				students.add(stu);
			}
			c.close();
		}
		return students;
	}

4:ContentProvider存储(从图片到视频都是数据库,都是contentprovider,必须用contentresolver访问.)和SQLite数据库
区别就是只能通过uri去操作数据

//自定义ContentProvider:


A:创建数据库表格
public class DBOpenHelper extends SQLiteOpenHelper {
	public DBOpenHelper(Context context, String name, int version) {
		super(context, name, null, version);
	}
	public void onCreate(SQLiteDatabase db) {
		db.execSQL("create table if not exists stutbl("
				+ "_id integer primary key autoincrement,"
				+ "name text not null," + "sex text not null,"
				+ "age integer not null" + ")");
		ContentValues values = new ContentValues();
		values.put("name", "张三");
		values.put("sex", "男");
		values.put("age", 19);
		db.insert("stutbl", null, values);
	}
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
	}
}

B:定义路径uri:

public class StudentInfo {
		public static final String AUTHORITY = "com.tarena.providers.stu";
		public static final String MULTI_PATH = "student";
		public static final String SINGLE_PATH = "student/#";
		public static final Uri CONENT_URI = Uri.parse("content://" + AUTHORITY+ "/" + MULTI_PATH);
		public static class Columns {
		public static final String ID = "_id";
		public static final String NAME = "name";
		public static final String SEX = "sex";
		public static final String AGE = "age";
	}
}

C:继承ContentProvider并增删改查:

public class StudentProvider extends ContentProvider {
	private static final int CODE_MULTI_STU = 1;
	private static final int CODE_SINGLE_STU = 2;
	private DBOpenHelper helper;
	private static UriMatcher matcher; // uri比较器.
	static {
		matcher = new UriMatcher(UriMatcher.NO_MATCH);
		matcher.addURI(StudentInfo.AUTHORITY, StudentInfo.MULTI_PATH,CODE_MULTI_STU);
		matcher.addURI(StudentInfo.AUTHORITY, StudentInfo.SINGLE_PATH,CODE_SINGLE_STU);
			}
	public boolean onCreate() {
		helper = new DBOpenHelper(getContext(), "stu.db", 1);
		return true;
	}
	public String getType(Uri uri) {
		return null;
	}
	
	//插入
	public Uri insert(Uri uri, ContentValues values) {
		Uri url = null;
		// 插入时,不能有指定id.否则就有语法错误.
		if (matcher.match(uri) != CODE_MULTI_STU) {
			throw new IllegalArgumentException("未知uri:" + uri);
		}
		SQLiteDatabase db = helper.getWritableDatabase();
		long rowId = db.insert("stutbl", null, values);
		db.close();
		if (rowId != -1) {
			url = ContentUris.withAppendedId(uri, rowId);
		}
		return url;
	}

	// 删除,主要为了获取where条件.
	public int delete(Uri uri, String selection, String[] selectionArgs) {
		// 判断uri 并处理条件
		String where = null;
		switch (matcher.match(uri)) {
		case CODE_MULTI_STU:// 多条数据访问
			where = selection;
			break;
		case CODE_SINGLE_STU:// 单条数据访问
			// 从uri中获取id
			long id = ContentUris.parseId(uri);
			// where条件.
			where = StudentInfo.Columns.ID + "=" + id;
			// 下面是死的,但有点难.
			if (selection != null)
				where += " and(" + selection + ")";
			break;
		default:
			throw new IllegalArgumentException("未知uri:" + uri);
		}
		SQLiteDatabase db = helper.getWritableDatabase();
		int count = db.delete("stutbl", where, selectionArgs);
		db.close();
		return count;
	}

	// 改,主要为了获取where条件.
	public int update(Uri uri, ContentValues values, String selection,
			String[] selectionArgs) {
		// 判断uri 并处理条件
		String where = null;
		switch (matcher.match(uri)) {
		case CODE_MULTI_STU:// 多条数据访问
			where = selection;
			break;
		case CODE_SINGLE_STU:// 单条数据访问
			// 从uri中获取id
			long id = ContentUris.parseId(uri);
			where = StudentInfo.Columns.ID + "=" + id;
			if (selection != null)
				where += " and(" + selection + ")";
			break;
		default:
			throw new IllegalArgumentException("未知uri:" + uri);
		}
		SQLiteDatabase db = helper.getWritableDatabase();
		int count = db.update("stutbl", values, where, selectionArgs);
		db.close();
		return count;
	}

	// 查询,主要为了获取where条件
	public Cursor query(Uri uri, String[] projection, String selection,
			String[] selectionArgs, String sortOrder) {
		// 判断uri 并处理条件
		String where = null;
		switch (matcher.match(uri)) {
		case CODE_MULTI_STU:// 多条数据访问
			where = selection;
			break;
		case CODE_SINGLE_STU:// 单条数据访问
			// 从uri中获取id
			long id = ContentUris.parseId(uri);
			where = StudentInfo.Columns.ID + "=" + id;
			if (selection != null)
				where += " and(" + selection + ")";
			break;
		default:
			throw new IllegalArgumentException("未知uri:" + uri);
		}
		SQLiteDatabase db = helper.getReadableDatabase();
		Cursor c = db.query("stutbl", projection, where, selectionArgs, null,
				null, sortOrder);
		return c;
	}
}

D:利用ContentResolver对ContentProvider进行操作处理:

private ContentResolver cr;
		cr = context.getContentResolver();
		
	 //向表中插入一条学员信息
	public long addStudent(Student stu) {
		long rowId = -1;
		ContentValues values = new ContentValues();
		values.put("name", stu.getName());
		values.put("sex", stu.getSex());
		values.put("age", stu.getAge());
		Uri uri = cr.insert(StudentInfo.CONTENT_URI, values);
		if (uri != null)
			rowId = ContentUris.parseId(uri);
		return rowId;
	}
	
	 //根据id 从表中移除一条信息
	public int removeStudent(int id) {
		int count = 0;
		count = cr.delete(ContentUris.withAppendedId(StudentInfo.CONTENT_URI,
				id), null, null);
		return count;
	}

	 //修改表中指定id的学员信息
	public int updateStudent(Student stu) {
		int count = 0;
		ContentValues values = new ContentValues();
		values.put("name", stu.getName());
		values.put("sex", stu.getSex());
		values.put("age", stu.getAge());
		count = cr.update(ContentUris.withAppendedId(StudentInfo.CONTENT_URI,
				stu.getId()), values, null, null);
		return count;
	}

	 //查询所有学员信息
	public ArrayList<Student> getStudents() {
		ArrayList<Student> students = null;
		Cursor c = cr.query(StudentInfo.CONTENT_URI, null, null, null, null);
		if (c != null) {
			students = new ArrayList<Student>();
			while (c.moveToNext()) {
				Student stu = new Student();
				stu.setId(c.getInt(c.getColumnIndex("_id")));
				stu.setName(c.getString(c.getColumnIndex("name")));
				stu.setSex(c.getString(c.getColumnIndex("sex")));
				stu.setAge(c.getInt(c.getColumnIndex("age")));
				students.add(stu);
			}
			c.close();
		}
		return students;
	}

Android系统提供的主要数据类型的ContentProvider,比如系统通讯录,图片,音频,视频,必须用contentresolver访问.实例如下:


sample1://获取sdcard图片信息

private ContentResolver cr;
	cr = context.getContentResolver();

	 //查询sd卡上的所有图片信息
	public ArrayList<ImageInfo> getImages() {
		ArrayList<ImageInfo> imgs = null;
		String[] projection = { "_id", "title" };//列名
		Cursor c = cr.query(Media.EXTERNAL_CONTENT_URI, projection, null, null,
				null);//外存储卡上遍历的结果集.
		if (c != null) {
			imgs = new ArrayList<ImageInfo>();
			while (c.moveToNext()) {
				ImageInfo info = new ImageInfo();
				info.setId(c.getInt(c.getColumnIndex("_id")));
				info.setTitle(c.getString(c.getColumnIndex("title")));
				imgs.add(info);
			}
			c.close();
		}
		return imgs;
	}

	 //根据id 获取指定图片
	public Bitmap getBitmap(int id) {
		try {//很强大的方法.
			return Media.getBitmap(cr, ContentUris.withAppendedId(
					Media.EXTERNAL_CONTENT_URI, id));
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	 //根据id 获取指定图片的缩略图
	public Bitmap getThumbnails(int id) {
		return Thumbnails.getThumbnail(cr, id, Thumbnails.MICRO_KIND, null);
	}

sample2://获取SDcard里的音乐

private ContentResolver resolver;
resolver = context.getContentResolver();

public ArrayList<Music> getLocalMusics() {
		ArrayList<Music> musics = null;
		String[] projection = { "_id", "title", "_data", "duration", "artist",
				"album", "album_key" };// 音频表列名.
		Cursor c = resolver.query(Media.EXTERNAL_CONTENT_URI, projection,
				"duration>20000", null, null);
		if (c != null && c.getCount() > 0) {
			musics = new ArrayList<Music>();
			while (c.moveToNext()) {
				Music music = new Music();
				music.setId(c.getInt(c.getColumnIndex("_id")));
				music.setName(c.getString(c.getColumnIndex("title")));
				music.setAlbum(c.getString(c.getColumnIndex("album")));
				music.setSinger(c.getString(c.getColumnIndex("artist")));
				music.setMusicPath(c.getString(c.getColumnIndex("_data")));
				music.setDuration(c.getInt(c.getColumnIndex("duration")));
				// 获取album_key
				String album_key = c.getString(c.getColumnIndex("album_key"));
				Cursor albumCursor = resolver.query(
						Albums.EXTERNAL_CONTENT_URI,
						new String[] { "album_art" }, "album_key = ?",
						new String[] { album_key }, null);
				// 根据album_key查找专辑图片路径
				if (albumCursor != null && albumCursor.moveToFirst()) {
					music.setAlbumPath(albumCursor.getString(0));
					albumCursor.close();
				}
				musics.add(music);
			}
			c.close();
		}
		return musics;
	}

sample3://查询系统通讯录

//修改xml权限 —>

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

//代码:

private ContentResolver cr;
		cr = context.getContentResolver();
		
		// 查询所有联系人的信息
		public ArrayList<ContactInfo> getContacts() {
		ArrayList<ContactInfo> contacts = null;
		Cursor c = cr.query(Contacts.CONTENT_URI, new String[] { Contacts._ID,
				Contacts.DISPLAY_NAME }, null, null, null);
		if (c != null) {
			contacts = new ArrayList<ContactInfo>();
			while (c.moveToNext()) {
				ContactInfo contact = new ContactInfo();
				contact.setId(c.getInt(c.getColumnIndex(Contacts._ID)));
				contact.setName(c.getString(c
						.getColumnIndex(Contacts.DISPLAY_NAME)));
				contact.setPhones(getPhones(contact.getId()));
				contact.setEmails(getEmails(contact.getId()));
				contacts.add(contact);
			}
			c.close();
		}
		return contacts;
	}
	
	// 根据联系人id获取联系人头像
	public Bitmap getPhoto(int contactId) {
		Uri uri = ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId);
		InputStream is = Contacts.openContactPhotoInputStream(cr, uri);
		Bitmap bm = BitmapFactory.decodeStream(is);
		return bm;
	}	
	
	// 根据联系人id 查询联系人邮箱信息
	private ArrayList<EmailInfo> getEmails(int contactId) {
		ArrayList<EmailInfo> emails = null;
		Cursor c = cr.query(Email.CONTENT_URI, new String[] { Email.DATA,
				Email.TYPE }, Email.CONTACT_ID + "=" + contactId, null, null);
		if (c != null) {
			emails = new ArrayList<EmailInfo>();
			while (c.moveToNext()) {
				EmailInfo email = new EmailInfo();
				email.setType(c.getInt(c.getColumnIndex(Email.TYPE)));
				email.setEmail(c.getString(c.getColumnIndex(Email.DATA)));
				emails.add(email);
			}
			c.close();
		}
		return emails;
	}
	
	// 根据联系人id 查询联系人电话信息
	private ArrayList<PhoneInfo> getPhones(int contactId) {
		ArrayList<PhoneInfo> phones = null;
		Cursor c = cr.query(Phone.CONTENT_URI, new String[] { Phone.NUMBER,
				Phone.TYPE }, Phone.CONTACT_ID + "=" + contactId, null, null);
		if (c != null) {
			phones = new ArrayList<PhoneInfo>();
			while (c.moveToNext()) {
				PhoneInfo phone = new PhoneInfo();
				phone.setType(c.getInt(c.getColumnIndex(Phone.TYPE)));
				phone.setNumber(c.getString(c.getColumnIndex(Phone.NUMBER)));
				phones.add(phone);
			}
			c.close();
		}
		return phones;
	}

sample4:向通讯录插入数据

//修改xml ------>

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

//代码:

ContentResolver cr = getContentResolver();
		
		Uri uri = Data.CONTENT_URI;
		// 向rawcontact插入空行,获取新插入行的id
		ContentValues values = new ContentValues();
		Uri newContact = cr.insert(RawContacts.CONTENT_URI, values);
		long raw_contact_id = ContentUris.parseId(newContact);

		// 插入姓名,必须满足三个信息(RAW_CONTACT_ID/MIMETYPE/value).
		values.clear();
		values.put(StructuredName.RAW_CONTACT_ID, raw_contact_id);
		values.put(StructuredName.MIMETYPE, StructuredName.CONTENT_ITEM_TYPE);
		values.put(StructuredName.DISPLAY_NAME, "王老五");
		cr.insert(uri, values);

		// 插入一个手机号码,必须满足三个信息.(RAW_CONTACT_ID/MIMETYPE/value).
		values.clear();
		values.put(Phone.RAW_CONTACT_ID, raw_contact_id);
		values.put(Phone.MIMETYPE, Phone.CONTENT_ITEM_TYPE);
		values.put(Phone.NUMBER, "18911520023");
		values.put(Phone.TYPE, Phone.TYPE_MOBILE);
		cr.insert(uri, values);

		// 插入一个家庭电话,必须满足三个信息.(RAW_CONTACT_ID/MIMETYPE/value).
		values.clear();
		values.put(Phone.RAW_CONTACT_ID, raw_contact_id);
		values.put(Phone.MIMETYPE, Phone.CONTENT_ITEM_TYPE);
		values.put(Phone.NUMBER, "01065585985");
		values.put(Phone.TYPE, Phone.TYPE_HOME);
		cr.insert(uri, values);
		
		// 插入一个私人邮箱,必须满足三个信息.(RAW_CONTACT_ID/MIMETYPE/value).
		values.clear();
		values.put(Email.RAW_CONTACT_ID, raw_contact_id);
		values.put(Email.MIMETYPE, Phone.CONTENT_ITEM_TYPE);
		values.put(Email.DATA, "zhangsan@163.com");
		values.put(Email.TYPE, Email.TYPE_HOME);
		cr.insert(uri, values);

		// 插入头像
		// 1:加载头像的图片到内存
		String path = "/mnt/sdcard/images/jintian.jpg";
		Options opts = new Options();
		opts.inJustDecodeBounds = true;
		BitmapFactory.decodeFile(path, opts);
		int xScale = opts.outWidth / 100;
		int yScale = opts.outHeight / 100;
		opts.inSampleSize = xScale > yScale ? xScale : yScale;
		opts.inJustDecodeBounds = false;
		Bitmap bm = BitmapFactory.decodeFile(path, opts);
		// 2:将头像图片信息保存到一个字节数组
		ByteArrayOutputStream os = new ByteArrayOutputStream();
		bm.compress(CompressFormat.JPEG, 100, os);
		values.clear();
		values.put(Photo.RAW_CONTACT_ID, raw_contact_id);
		values.put(Photo.MIMETYPE, Photo.CONTENT_ITEM_TYPE);
		values.put(Photo.PHOTO, os.toByteArray());
		cr.insert(uri, values);

sample5:查询通讯录

ContentResolver cr;
		cr = context.getContentResolver();
		
		// 根据号码是否存在,取出姓名.若存在,则取姓名,否则号码显示.
		private CursorWrapper getCursorWrapper(Cursor c) {
		CursorWrapper cursor = new CursorWrapper(c) {
			public String getString(int columnIndex) {
				// 如果当前查询列为电话号码列
				if (super.getColumnIndex("contact") == columnIndex) {
					// 取联系人号码
					String contact = super.getString(columnIndex);
					// 根据号码在联系人表中查询联系人姓名路径Uri.
					Uri lookupUri = Uri
							.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI,
									Uri.encode(contact));
					Cursor c1 = cr.query(lookupUri, null, null, null, null);
					// 如果存在该联系人,则获取其姓名
					if (c1 != null && c1.moveToFirst()) {
						contact = c1.getString(c1
								.getColumnIndex(PhoneLookup.DISPLAY_NAME));
						c1.close();
					}
					// 返回电话号码或联系人姓名
					return contact;
				}
				return super.getString(columnIndex);
			}                                                                                                                                                                                                                                                                                                                              
		};
		return cursor;
	}

	// 获取所有会话信息,会话列表
	public ArrayList<ConversationBean> getConversations() {
		ArrayList<ConversationBean> conversationBeans = null;
		Uri uri = Uri.parse("content://sms/conversations");
		String[] projection = { "groups.group_thread_id as thread_id",
				"groups.group_date as last_date", "groups.msg_count as count",
				"sms.address as contact", "sms.body as content" };
		Cursor c = cr.query(uri, projection, null, null,
				"groups.group_date desc");
		if (c != null) {
			Cursor cursor = getCursorWrapper(c);
			// 初始化集合
			conversationBeans = new ArrayList<ConversationBean>();
			// 遍历查询结果
			while (cursor.moveToNext()) {
				ConversationBean con = new ConversationBean();
				con.setId(cursor.getInt(cursor.getColumnIndex("thread_id")));
				con.setContact(cursor.getString(cursor
						.getColumnIndex("contact")));
				con.setContent(cursor.getString(cursor
						.getColumnIndex("content")));
				con.setDate(cursor.getLong(cursor.getColumnIndex("last_date")));
				con.setMsgCount(cursor.getInt(cursor.getColumnIndex("count")));
				conversationBeans.add(con);
			}
			cursor.close();
		}
		return conversationBeans;
	}

	 //根据会话id 查询会话内的短消息,短信详情
	public ArrayList<MessageInfo> getMessages(int thread_id) {
		ArrayList<MessageInfo> messages = null;
		Uri uri = Uri.parse("content://sms/");
		String[] projection = { "_id", "address as contact", "body as content",
				"date", "type" };
		Cursor c = cr.query(uri, projection, "thread_id=" + thread_id, null,
				"date desc");
		if (c != null) {
			messages = new ArrayList<MessageInfo>();
			Cursor cursor = getCursorWrapper(c);
			while (cursor.moveToNext()) {
				MessageInfo info = new MessageInfo();
				info.setId(cursor.getInt(cursor.getColumnIndex("_id")));
				info.setContact(cursor.getString(cursor
						.getColumnIndex("contact")));
				info.setDate(cursor.getLong(cursor.getColumnIndex("date")));
				info.setContent(cursor.getString(cursor
						.getColumnIndex("content")));
				info.setType(cursor.getInt(cursor.getColumnIndex("type")));
				messages.add(info);
			}
			cursor.close();
		}
		return messages;
	}
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值