recently made a simple SMS operation module, relatively practical small. The main function is to send text messages (including the status of text messages), stored text messages (can be used for text message list display, etc.), SMS storage can be used SQLite, but think also on dozens of hundreds of text messages, with SQLite is overqualified, also trouble, So I decided to use Sharepreference to do this module with the object serialization.
The first is the text message entity class, in order to reuse, to make abstract class, then the specific project use as long as the inheritance of the abstract class can:
Public abstract class Message implements serializable{private String number;//private int playtime;private int id;private String Username;private string Messagetext;private string Time;public Message (string number, int playTime, int ID, string Username,string MessageText, String time) {super (); this.number = Number;//this.playtime = Playtime;this.id = Id;this.use Rname = Username;this.messagetext = Messagetext;this.time = time;} Public String GetNumber () {return number;} public void Setnumber (String number) {this.number = number;} public int getId () {return ID;} public void setId (int id) {this.id = ID;} Public String GetUserName () {return userName;} public void Setusername (String userName) {this.username = UserName;} Public String Getmessagetext () {return messagetext;} public void Setmessagetext (String messagetext) {this.messagetext = MessageText;} Public String GetTime () {return time;} public void SetTime (String time) {this.time = time;} @Overridepublic String toString () {//TODO auto-generated MeThod stubreturn "Number:" +this.number+ ", User:" +this.username+ ", Number:" +this.id+ ", SMS Content:" +this.messagetext;}}
Have several text messages that must be the data as member variables, and then re-tostring the method.
Core Operation class, Messageutils, has to send the text message method, including after sending the message to save, SMS send success or not, receive the status of the feedback function, to a single text message and all SMS access to provide external interface, the use of the time is very convenient:
public class Messageutils {//private Message message;private Context context;private String sent_sms_action = "Sent_sms_a Ction "; Private String delivered_sms_action = "Delivered_sms_action"; Intentprivate Intent Sentintent carrying the successful status of the transmission; Private Pendingintent SENTPI; The intentprivate Intent Deliverintent carrying the receiving success status; Private Pendingintent Deliverpi; Public Messageutils (Context context) {super (); this.context = Context;sentintent = new Intent (sent_sms_action); Deliverintent = new Intent (delivered_sms_action);} /** * Serialized Object * @param message * @return * @throws IOException */private String serialize (Message message) throws Ioexceptio n {bytearrayoutputstream bytearrayoutputstream = new Bytearrayoutputstream (); ObjectOutputStream ObjectOutputStream = new ObjectOutputStream (bytearrayoutputstream); Objectoutputstream.writeobject (message); String serstr = bytearrayoutputstream.tostring ("iso-8859-1"); Serstr = Java.net.URLEnCoder.encode (Serstr, "UTF-8"); Objectoutputstream.close (); Bytearrayoutputstream.close (); return serstr; }/** * Deserialize the object * * @param str will be converted to an object string * @return * @throws IOException * @throws C Lassnotfoundexception */Private Message deserialization (String str) throws IOException, ClassNotFound Exception {if (str = = NULL | | str = = "") {return null; } String redstr = Java.net.URLDecoder.decode (str, "UTF-8"); Bytearrayinputstream Bytearrayinputstream = new Bytearrayinputstream (redstr.getbytes ("ISO-8859-1")); ObjectInputStream ObjectInputStream = new ObjectInputStream (bytearrayinputstream); Message message = (message) objectinputstream.readobject (); Objectinputstream.close (); Bytearrayinputstream.close (); return message; }/** * Save SMS * @param strobject sequenceText message object converted to String * @param num SMS Storage Sequence number */private void savemessage (message message,int num) {String Strob ject;try {String i = string.valueof (num); strobject = serialize (message); Sharedpreferences sp = context.getsharedpreferences ("Message", 0); Editor edit = Sp.edit (); Edit.putstring (i, strobject); Edit.commit (); Reset SMS Total number of setsmscount (num);} catch (IOException e) {//TODO auto-generated catch Blocke.printstacktrace ();} }/** * Delete an SMS * @param num deleted SMS Storage ordinal */public void deleteMessage (int num) {int sum = g Etsmscount (); if (sum = = num) {setsmscount (--sum); Return } for (int i = Num;i < sum;i++) {Message message = GetMessage (i+1); Savemessage (message, I); }//int count = Getsmscount ();//Setsmscount (--count);} /** * Get a text message * @param num SMS Storage ordinal number * @return */public Message getMessage (int num) {sharedpref Erences SP = CONTEXT.GETSHAREDPREferences ("Message", 0); Message message; String i = string.valueof (num); try {message = deserialization (sp.getstring (i, null)); return message;} catch (Classnotfou Ndexception e) {//Todo auto-generated catch Blocke.printstacktrace (); return null;} catch (IOException e) {//Todo Auto-ge Nerated catch Blocke.printstacktrace (); return null;} /** * Get all stored SMS * @return */public list<message> getallmessage () {list<message> mes Sages = new arraylist<message> (); for (int i = 1;i <= getsmscount (); i++) {Message message = GetMessage (i); messages. Add (message);} return messages;} /** * Send text messages, register to send status broadcasts and receive status broadcasts, store them every text message sent * @param messagetext SMS content * @param num OFFSET number * * public void SE Ndmessage (Message message) {Smsmanager Smsmanager = Smsmanager.getdefault (); SENTPI = pendingintent.getbroadcast (context, 0, sentintent, 0); Deliverpi = pendingintent.getbroadcast (context, 0, deliverintent, 0); Regsendbroadcast (); Regrecbroadcast (); list<string> dividecontents = Smsmanager.dividemessage (Message.getmessagetext ()); for (String text:dividecontents) {smsmanager.sendtextmessage (Message.getnumber (), NULL, text, SENTPI, delive RPI); } int count = Getsmscount (); Each SMS message is stored savemessage (message, ++count); /** * Register to send status broadcast, wait for the operator to return the result code, according to the result code to respond accordingly */private void Regsendbroadcast () {Context.registerrec Eiver (New Broadcastreceiver () {@Override public void onreceive (Context _context, Intent _intent ) {switch (Getresultcode ()) {case ACTIVITY.RESULT_OK: Toast.maketext (context, "message sent successfully", Toast.length_short). Show (); Break Case SmsManager.RESULT_ERROR_GENERIC_FAILURE:Toast.makeText (Context, "SMS Send Failed", Toast.length_short). Show (); Break Case SmsManager.RESULT_ERROR_RADIO_OFF:Toast.makeText (context, "SMS send Failed", to Ast. Length_short). Show (); Break Case SmsManager.RESULT_ERROR_NULL_PDU:Toast.makeText (context, "SMS Send Failed", Toas T.length_short). Show (); Break }}}, new Intentfilter (sent_sms_action)); /** * Register SMS Receive status broadcast, once receive Fangcheng receive SMS receive broadcast */private void Regrecbroadcast () {Context.registerreceiver (n EW Broadcastreceiver () {@Override public void onreceive (Context _context, Intent _intent) {T Oast.maketext (Context, "Recipient has successfully received", Toast.length_short). Show (); }}, new Intentfilter (delivered_sms_action)); /** * Set SMS number record * @param count */private void Setsmscount (int count) {sharedpreferences SP = context.getsharedpreferences ("Message", 0); Editor edit = Sp.edit (); Edit.putint ("Smscount", count); Edit.commit (); }/** * Get the total number of messages stored in SMS * @return */public int getsmscount () {Sharedpreferences sp = CONTEXT.GETSHAREDP References ("Message", 0); int count = Sp.getint ("Smscount", 0); return count;} }
Converts a Message object into a string object using serialization and deserialization of the object, storing it in sharepreference, and the key value is the sequence number of the text message. This sequence number allows you to query or delete a specified text message.
Such a single project needs to SMS operation and need to store text messages, you can use this small module, only need a Messageutils object, call its public method can not only facilitate the operation of text messages, in line with object-oriented high-aggregation low-coupling, reusable design principles.
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Simple SMS Operation module for Android development