Phone operations that Android uses frequently

Source: Internet
Author: User
Tags bulk insert

To share one of my Android tool class, to get all kinds of information inside the phone, including making calls. Get all contact names and phone numbers, insert contact name and phone number, insert contact name and phone number. Insert Call history. Get all the user text messages. Bulk Insert SMS, read files from SDcard, write files to 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 {/* * detects if sdcard is normal */public static Boolean Checksdcard () {return environment.getexternalstorage State (). Equals (environment.media_mounted);} /* * Read file from sdcard */public static string Readfilefromsdcard (string path, string filename) throws IOException {if (!CHECKSDCA RD ()) {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 = InS Tream.read (buffer))! =-1) {outstream.write (buffer, 0, Len);} byte[] data = Outstream.tobytearray (); Outstream.close (); Instream.close (); return new String (data); /* * Write file to SDcard */public static Boolean Writefiletosdcard (string path, String filename,string content, Boolean append) th Rows 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;} /* * Call */public static void Callphone (String number, context context) {Intent Intent = new Intent (); Intent.setaction (in Tent. Action_call); Intent.setdata (Uri.parse ("Tel:" + number); context.startactivity (intent);} /* * Get all contact names and phone */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 ()) {// Get the name String name = Cur.getstring (Cur.getcolumnindex (ContactsContract.Contacts.DISPLAY_NAME));//Get Phone number string ContactId = cur.getstring (Cur.getcolumnindex (contactscontract.contacts._id)); Gets the ID number of the contact, the database in SQLite idcursor 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)); Phone Number field contact may have more than one resultlist.add (new Contactsinfo (name, Strphonenumber));}} return resultlist;} /* Insert contact name and phone */public static void Insertcontacts (string name, String Number,context Context) {if (name = = NULL | | numbe r = = null) return; Contentresolver CR = Context.getcontentresolver ();//First run a null-value insert to Rawcontacts.content_uri, The goal is to obtain the system return rawcontactidcontentvalues values = new Contentvalues (); Uri Rawcontacturi = Cr.insert (Rawcontacts.content_uri, values); Long Rawcontactid = Contenturis.parseid (RawContactUri) Values.clear ();//Enter the data table into the name 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 table into the telephone 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);} /* * BULK INSERT Contact name and phone */public static void Insertcontactslist (List<contactsinfo> listdata,context Context) throws Exception {//Document location:reference\android\provider\contactscontract.rawcontacts.htmlarraylist< contentprovideroperation> Ops = new arraylist<contentprovideroperation> (); Contentresolver CR = Context.getcontentresolver ();//insert information for the first few people int rawcontactinsertindex = 0;for (int i = 0; i < Listdat A.size (); i++) {Contactsinfo info = listdata.get (i);//Insert the blank line of the current numbered person Ops.add (Contentprovideroperation.newinsert ( Rawcontacts.content_uri). Withvalue (Rawcontacts.account_type, null). Withvalue (Rawcontacts.account_name, NULL). Build ());//Insert the last name of the current numbering personName 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 ());// Insert the phone Ops.add (Contentprovideroperation.newinsert (Android.provider.ContactsContract.Data.CONTENT_URI) of the current numbered person. 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 ();}} /* * Insert Call log */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 has seen 1 not seen Context.getcontentresolver (). Insert (CallLog.Calls.CONTENT _uri, values);} return true;} /* * Get user all SMS */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"));p Honenumber = cur.getstring ( Cur.getcolumnindex ("Address")); smsbody = cur.getstring (Cur.getcolumnindex ("Body"));d ate = 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, Ty PE));}} catch (Sqliteexception ex) {}return list;} /* * BULK INSERT SMS */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 < i++) {byte byte0 = tmp[i]; str[k++] = hexdigits[byte0 >>> 4 & 0xf]; str[k++] = hex Digits[byte0 & 0XF]; }s = new String (str). toUpperCase (); } catch (Exception e) {}return s;}}

The javabean involved in the above

Package Com.canlong.javabean;public class Calllogmodel {private String number;private long date;private long duration;// In seconds private int TYPE;//1 Call 2 dialed 3 not received private int rend;//0 has seen 1 not seen public Calllogmodel () {}public Calllogmodel (String number, lo ng date, long duration, int type,int rend) {this.number = Number;this.date = date;this.duration = Duration;this.type = Typ E;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;} @Overridepublic 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;//contact private string number;//Contact number Private String content;private long date;private int read;//0 unread 1 read private int type;//Contact Type 1 receive 2 send 3 draft public Smsinfo () {}public S MSInfo (String Linkman, string number, string content, long Date,int type) {This.linkman = Linkman;this.number = Number;thi S.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.N umber = 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;} @Overridepublic String toString () {return "Smsinfo [linkman=" + Linkman + ", number=" + number+ ", content=" + content + " , date= "+ Date +", type= "+ type+"] ";}}



Phone operations that Android uses frequently

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.