android - How to get unread SMS when just receive it? -
i'm building unread sms relay application. there phone , b, when receives sms , no 1 read it, application relay b. find when receives sms, there system notification display. contentobserver
's onchange()
method called until disappear notification. should unread sms when receive it?
contentobserver:
public newincomingcontentobserver(handler handler, application application) { super(handler); this.mapplication = application; } @override public void onchange(boolean selfchange) { system.out.println(selfchange); super.onchange(selfchange); uri uri = uri.parse(sms_uri_inbox); mmessagelistener.onreceived(this.getsmsinfo(uri, mapplication)); } /** * newest sms */ private smsinfo getsmsinfo(uri uri, application application) { ... } public interface messagelistener { public void onreceived(smsinfo smsinfo); } public void setonreceivedmessagelistener( messagelistener messagelistener) { this.mmessagelistener = messagelistener; } }
service:
public class smslistenerservice extends service { public static final string uri = "content://sms/inbox"; public smslistenerservice() { } @override public ibinder onbind(intent intent) { throw new unsupportedoperationexception("not yet implemented"); } @override public int onstartcommand(intent intent, int flags, int startid) { //register observer newincomingcontentobserver smscontentobserver = new newincomingcontentobserver(new handler(), getapplication()); this.getcontentresolver().registercontentobserver (uri.parse(uri), true, smscontentobserver); smscontentobserver.setonreceivedmessagelistener(new newincomingcontentobserver.messagelistener() { @override public void onreceived(smsinfo smsinfo) { system.out.println(smsinfo); } }); return start_not_sticky; } }
an example borrowed (https://github.com/pyo25/phonegap-sms-reception-plugin), example phonegap plugin can still use it:
public class smsreceiver extends broadcastreceiver { public static final string sms_extra_name = "pdus"; // broadcast boolean used continue or not message broadcast // other broadcastreceivers waiting incoming sms (like native sms app) private boolean broadcast = false; @override public void onreceive(context ctx, intent intent) { // sms map intent bundle extras = intent.getextras(); if (extras != null) { // received sms array object[] smsextra = (object[]) extras.get(sms_extra_name); (int i=0; < smsextra.length; i++) { smsmessage sms = smsmessage.createfrompdu((byte[]) smsextra[i]); string formattedmsg = sms.getoriginatingaddress() + ">" + sms.getmessagebody(); } // if plugin active , don't want broadcast other receivers if (!broadcast) { this.abortbroadcast(); } } } }
and in androidmanifest:
<uses-permission android:name="android.permission.receive_sms"/>