android经常使用的电话操作[通俗易懂]

android经常使用的电话操作

大家好,又见面了,我是全栈君。

给大家分享一下我的一个Android工具类,能够获取手机里面的各种信息,包含拨打电话。 获取全部联系人姓名及电话,插入联系人姓名及电话,插入联系人姓名及电话。插入通话记录。获取用户全部短信。批量插入短信,读取文件从SDcard,写入文件到SDcard。

。。。。

package com.canlong.util;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import android.content.ContentProviderOperation;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteException;
import android.net.Uri;
import android.os.Environment;
import android.provider.CallLog;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.provider.ContactsContract.CommonDataKinds.StructuredName;
import android.provider.ContactsContract.RawContacts;
import android.provider.ContactsContract.RawContacts.Data;

import com.canlong.javabean.CallLogModel;
import com.canlong.javabean.ContactsInfo;
import com.canlong.javabean.SmsInfo;

public class Util {
	/*
	 * 检測SDcard是否正常
	 */
	public static boolean checkSDcard() {
		return Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED);
	}

	/*
	 * 读取文件从SDcard
	 */
	public static String readFileFromSDcard(String path, String filename)
			throws IOException {
		if (!checkSDcard()) {
			return null;
		}
		path = Environment.getExternalStorageDirectory().getAbsolutePath()
				+ "/" + path;
		File dir = new File(path);
		if (!dir.exists())
			dir.mkdirs();

		FileInputStream inStream = new FileInputStream(new File(dir, filename));
		ByteArrayOutputStream outStream = new ByteArrayOutputStream();
		byte[] buffer = new byte[1024];
		int len = 0;
		while ((len = inStream.read(buffer)) != -1) {
			outStream.write(buffer, 0, len);
		}
		byte[] data = outStream.toByteArray();
		outStream.close();
		inStream.close();
		return new String(data);
	}

	/*
	 * 写入文件到SDcard
	 */
	public static boolean writeFileToSDcard(String path, String filename,
			String content, boolean append) throws IOException {
		byte[] buffer = content.getBytes();
		if (!checkSDcard()) {
			return false;
		}
		path = Environment.getExternalStorageDirectory().getAbsolutePath()
				+ "/" + path;
		File dir = new File(path);
		if (!dir.exists())
			dir.mkdirs();
		FileOutputStream out = new FileOutputStream(new File(dir, filename),
				append);
		out.write(buffer);
		out.flush();
		out.close();
		return true;
	}

	/*
	 * 拨打电话
	 */

	public static void callPhone(String number, Context context) {
		Intent intent = new Intent();
		intent.setAction(Intent.ACTION_CALL);
		intent.setData(Uri.parse("tel:" + number));
		context.startActivity(intent);
	}

	/*
	 * 获取全部联系人姓名及电话
	 */

	public static List<ContactsInfo> getAllContacts(Context context) {
		List<ContactsInfo> resultList = new ArrayList<ContactsInfo>();

		ContentResolver cr = context.getContentResolver();
		Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null,
				null, null, null);
		while (cur.moveToNext()) {
			// 得到名字
			String name = cur.getString(cur
					.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
			// 得到电话号码
			String contactId = cur.getString(cur
					.getColumnIndex(ContactsContract.Contacts._ID)); // 获取联系人的ID号,在SQLite中的数据库ID
			Cursor phone = cr.query(
					ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
					ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = "
							+ contactId, null, null);
			while (phone.moveToNext()) {
				String strPhoneNumber = phone
						.getString(phone
								.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)); // 手机号码字段联系人可能不止一个
				resultList.add(new ContactsInfo(name, strPhoneNumber));
			}
		}

		return resultList;
	}

	/*
	 * 插入联系人姓名及电话
	 */

	public static void insertContacts(String name, String number,
			Context context) {
		if (name == null || number == null)
			return;
		ContentResolver cr = context.getContentResolver();
		// 首先向RawContacts.CONTENT_URI运行一个空值插入,目的是获取系统返回的rawContactId
		ContentValues values = new ContentValues();
		Uri rawContactUri = cr.insert(RawContacts.CONTENT_URI, values);
		long rawContactId = ContentUris.parseId(rawContactUri);
		values.clear();
		// 往data表入姓名数据
		values.put(Data.RAW_CONTACT_ID, rawContactId);
		values.put(Data.MIMETYPE, StructuredName.CONTENT_ITEM_TYPE);
		values.put(StructuredName.DISPLAY_NAME, name);
		cr.insert(ContactsContract.Data.CONTENT_URI, values);

		// 往data表入电话数据
		values.clear();
		values.put(ContactsContract.Contacts.Data.RAW_CONTACT_ID, rawContactId);
		values.put(Data.MIMETYPE, Phone.CONTENT_ITEM_TYPE);
		values.put(Phone.NUMBER, number);
		values.put(Phone.TYPE, Phone.TYPE_MOBILE);
		cr.insert(ContactsContract.Data.CONTENT_URI, values);

	}

	/*
	 * 批量插入联系人姓名及电话
	 */

	public static void insertContactsList(List<ContactsInfo> listData,
			Context context) throws Exception {
		// 文档位置:reference\android\provider\ContactsContract.RawContacts.html
		ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
		ContentResolver cr = context.getContentResolver();

		// 插入第几个人的信息
		int rawContactInsertIndex = 0;

		for (int i = 0; i < listData.size(); i++) {
			ContactsInfo info = listData.get(i);
			// 插入当前编号人的空行
			ops.add(ContentProviderOperation.newInsert(RawContacts.CONTENT_URI)
					.withValue(RawContacts.ACCOUNT_TYPE, null)
					.withValue(RawContacts.ACCOUNT_NAME, null).build());
			// 插入当前编号人的姓名
			ops.add(ContentProviderOperation
					.newInsert(
							android.provider.ContactsContract.Data.CONTENT_URI)
					.withValueBackReference(Data.RAW_CONTACT_ID,
							rawContactInsertIndex)
					.withValue(Data.MIMETYPE, StructuredName.CONTENT_ITEM_TYPE)
					.withValue(StructuredName.GIVEN_NAME, info.getName())
					.build());
			// 插入当前编号人的电话
			ops.add(ContentProviderOperation
					.newInsert(
							android.provider.ContactsContract.Data.CONTENT_URI)
					.withValueBackReference(Data.RAW_CONTACT_ID,
							rawContactInsertIndex)
					.withValue(Data.MIMETYPE, Phone.CONTENT_ITEM_TYPE)
					.withValue(Phone.NUMBER, info.getNumber())
					.withValue(Phone.TYPE, Phone.TYPE_MOBILE).build());
			// rawContactInsertIndex++;
			cr.applyBatch(ContactsContract.AUTHORITY, ops);
			ops.clear();
		}
	}

	/*
	 * 插入通话记录
	 */
	
	public static boolean insertCallLog(List<CallLogModel> listDate,Context context){
		
		for(int i=0;i<listDate.size();i++){
			CallLogModel info = listDate.get(i);
			ContentValues values = new ContentValues(); 
		    values.put(CallLog.Calls.NUMBER, info.getNumber());
		    values.put(CallLog.Calls.DATE, info.getDate());
		    values.put(CallLog.Calls.DURATION, info.getDuration());
		    values.put(CallLog.Calls.TYPE,info.getType());
		    values.put(CallLog.Calls.NEW, info.getRend());//0已看1未看 
		    context.getContentResolver().insert(CallLog.Calls.CONTENT_URI, values);
		}
		return true;
	}
	
	
	/*
	 * 获取用户全部短信
	 */
	public static List<SmsInfo> getAllSms(Context context) {
		List<SmsInfo> list = new ArrayList<SmsInfo>();
		final String SMS_URI_ALL = "content://sms/";
		try {
			ContentResolver cr = context.getContentResolver();
			String[] projection = new String[] { "_id", "address", "person",
					"body", "date", "type" };
			Uri uri = Uri.parse(SMS_URI_ALL);
			Cursor cur = cr.query(uri, projection, null, null, "date desc");

			while (cur.moveToNext()) {
				String name;
				String phoneNumber;
				String smsbody;
				long date;
				int type;

				name = cur.getString(cur.getColumnIndex("person"));
				phoneNumber = cur.getString(cur.getColumnIndex("address"));
				smsbody = cur.getString(cur.getColumnIndex("body"));

		
				date = Long.parseLong(cur.getString(cur
						.getColumnIndex("date")));

				type = cur.getInt(cur.getColumnIndex("type"));
				
				// Uri personUri = Uri.withAppendedPath(
				// ContactsContract.PhoneLookup.CONTENT_FILTER_URI,
				// phoneNumber);
				// Cursor localCursor = cr.query(personUri, new String[] {
				// PhoneLookup.DISPLAY_NAME, PhoneLookup.PHOTO_ID,
				// PhoneLookup._ID }, null, null, null);
				//
				// if (localCursor.getCount() != 0) {
				// localCursor.moveToFirst();
				// name = localCursor.getString(localCursor
				// .getColumnIndex(PhoneLookup.DISPLAY_NAME));
				// }
				if (smsbody == null)
					smsbody = "";
				list.add(new SmsInfo(name, phoneNumber, smsbody, date, type));
			}
		} catch (SQLiteException ex) {

		}

		return list;
	}

	/*
	 * 批量插入短信
	 */
	public static boolean insertSmsList(List<SmsInfo> listData, Context context) {
		Uri mSmsUri = Uri.parse("content://sms/inbox");
		for (int i = 0; i < listData.size(); i++) {
			SmsInfo info = listData.get(i);
			ContentValues values = new ContentValues();
			values.put("address", info.getNumber());
			values.put("body", info.getContent());
			values.put("date", info.getDate());
			values.put("read", info.getRead());
			values.put("type", info.getType());
			//values.put("service_center", "+8613010776500");
			context.getContentResolver().insert(mSmsUri, values);
		}
		return true;
	}
	public static String getMD5(String instr) {
		String s = null;
		char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
				'a', 'b', 'c', 'd', 'e', 'f' };
		try {
			java.security.MessageDigest md = java.security.MessageDigest
					.getInstance("MD5");
			md.update(instr.getBytes());
			byte tmp[] = md.digest();
			char str[] = new char[16 * 2]; 
			int k = 0; 
			for (int i = 0; i < 16; i++) {
				byte byte0 = tmp[i]; 
				str[k++] = hexDigits[byte0 >>> 4 & 0xf]; 
				str[k++] = hexDigits[byte0 & 0xf]; 
			}
			s = new String(str).toUpperCase(); 
		} catch (Exception e) {
		}
		return s;
	}
}

以上所涉及到的JavaBean

package com.canlong.javabean;

public class CallLogModel {
	private String number;
	private long date;
	private long duration;//以秒为单位
	private int type;//1来电 2已拨 3未接
	private int rend;//0已看1未看 
	public CallLogModel(){}
	public CallLogModel(String number, long date, long duration, int type,
			int rend) {
		this.number = number;
		this.date = date;
		this.duration = duration;
		this.type = type;
		this.rend = rend;
	}
	public String getNumber() {
		return number;
	}
	public void setNumber(String number) {
		this.number = number;
	}
	public long getDate() {
		return date;
	}
	public void setDate(long date) {
		this.date = date;
	}
	public long getDuration() {
		return duration;
	}
	public void setDuration(long duration) {
		this.duration = duration;
	}
	public int getType() {
		return type;
	}
	public void setType(int type) {
		this.type = type;
	}
	public int getRend() {
		return rend;
	}
	public void setRend(int rend) {
		this.rend = rend;
	}
	@Override
	public String toString() {
		return "CallLogModel [number=" + number + ", date=" + date
				+ ", duration=" + duration + ", type=" + type + ", rend="
				+ rend + "]";
	}
	
}

package com.canlong.javabean;

public class ContactsInfo {
	private String name;
	private String number;
	
	
	public ContactsInfo(){}
	
	public ContactsInfo(String name, String number) {
		this.name = name;
		this.number = number;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getNumber() {
		return number;
	}
	public void setNumber(String number) {
		this.number = number;
	}
	
	
}

package com.canlong.javabean;

public class SmsInfo {
	private String linkman;//联系人
	private String number;//联系号码
	private String content;
	private long date;
	private int read;//0未读 1已读
	private int type;//联系类型 1接收 2发送  3草稿 

	public SmsInfo(){}
	public SmsInfo(String linkman, String number, String content, long date,
			int type) {
		this.linkman = linkman;
		this.number = number;
		this.content = content;
		this.date = date;
		this.type = type;
	}
	
	public SmsInfo(String linkman, String number, String content, long date,
			int read, int type) {
		this.linkman = linkman;
		this.number = number;
		this.content = content;
		this.date = date;
		this.read = read;
		this.type = type;
	}
	public int getRead() {
		return read;
	}
	public void setRead(int read) {
		this.read = read;
	}
	public String getLinkman() {
		return linkman;
	}
	public void setLinkman(String linkman) {
		this.linkman = linkman;
	}
	public String getNumber() {
		return number;
	}
	public void setNumber(String number) {
		this.number = number;
	}
	public String getContent() {
		return content;
	}
	public void setContent(String content) {
		this.content = content;
	}
	 
	public long getDate() {
		return date;
	}
	public void setDate(long date) {
		this.date = date;
	}
	public int getType() {
		return type;
	}
	public void setType(int type) {
		this.type = type;
	}
	@Override
	public String toString() {
		return "SmsInfo [linkman=" + linkman + ", number=" + number
				+ ", content=" + content + ", date=" + date + ", type=" + type
				+ "]";
	}
	
}

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/116025.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • JAVA程序员简历模板_Java工程师简历模板

    JAVA程序员简历模板_Java工程师简历模板Java程序员简历模板本简历模板由国内首家互联网人才拍卖网站「 JobDeer.com 」提供。(括号里的是我们的顾问编写的说明,建议在简历书写完成后统一删除)先讲讲怎样才是一份好的技术简历首先,一份好的简历不光说明事实,更通过FAB模式来增强其说服力。Feature:是什么Advantage:比别人好在哪些地方Benefit:如果雇佣你,招聘方会得到什么好

    2025年6月25日
    12
  • 河北2021普通高考理科成绩查询,2019年河北高考一分一段表 文科理科成绩排名查询…[通俗易懂]

    河北2021普通高考理科成绩查询,2019年河北高考一分一段表 文科理科成绩排名查询…[通俗易懂]2019年河北省普通高校招生文理科考生成绩统计表最新!2019年河北省普通高校招生文理科考生一分一档统计表公布!河北考生和家长可登录河北省教育考试院官方网站(http://www.hebeea.edu.cn)查询《2019年河北省普通高校招生各类考生成绩统计表》。2019年河北省普通高校招生文理科一分一档统计表2019河北高考一分一档统计表公布2019河北高考一分一档统计表公布22019河北高考一…

    2022年7月14日
    13
  • 理解几种常见的进程间通信方式

    理解几种常见的进程间通信方式什么是进程间通信广义上讲,进程间通信(Inter-ProcessCommunication,IPC)是指运行在不同进程(不论是否在同一台机器)中的若干线程间的数据交换。从上面的定义可以得出两点:参与通信的进程即可以运行在同一台机器上,也可以运行在各自的设备环境中(RemoteProcedureCallProtocol,RPC)。如果进程是跨机器运行的,则通常是由网络连接在一起。实现方

    2022年10月9日
    0
  • 【知识图谱】知识推理[通俗易懂]

    【知识图谱】知识推理[通俗易懂]文章目录一、本体知识推理简介1、OWL本体语言(1)OWL本体语言概述(2)描述逻辑一、本体知识推理简介1、OWL本体语言(1)OWL本体语言概述OWL的特性:OWL本体语言是知识图谱中最规范(W3C制定)、最严谨(采用描述逻辑)、表达能力最强(是一阶谓词逻辑的子集)的语言;它基于RDF语法,使表示出来的文档具有语义理解的结构基础。促进了统一词汇表的使用,定义了丰富的语义词汇。允…

    2022年6月11日
    28
  • 计算机适配器有什么作用,例举适配器是什么

    计算机适配器有什么作用,例举适配器是什么随着科技进步,网络的进步,电脑已逐渐渗透到我们生活的方方面面,但是我们对于电脑的一些配置却不怎么了解,比如我们经常用到的适配器。下面,我就将适配器的一些小知识分享给大家我们在生活中或者使用电脑的时候经常会看到适配器一词,很多朋友就纳闷了,适配器是什么呢?有什么作用呢?针对这些问题,小编给大家整理了一些适配器的介绍,赶紧来瞧瞧吧适配器介绍电脑图解1适配器是一个接口转换器,也就是一种起中间连接作用的配…

    2022年6月7日
    49
  • c++开发面试问题(java面试app)

    面试智力题1、25皮马,5个赛道,求经过几场比赛,可以得到跑得最快的5皮马1)先把25皮马分成5组,分别每组进行比赛:(5场)A1A2A3A4A5、B1B2B3B4B5、C1C2C3C4C5、D1D2D3D4D5、E1E2E3E4E5。假设每组比赛后,结果如上所示。2)把每组最快的马拿出来进行比赛:(1场)A1B1…

    2022年4月10日
    42

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号