后台Web服务从特定号码接收短信

时间:2016-09-06 04:26:42

标签: android web-services sms android-notifications

我通过短信接收lat-lng,但我想在通知中显示我的短信主体。从特定号码(如+923030503860)收到短信时。 我正在阅读本教程Receiving in app SMS messages only from certain specified numbers  但无法找到解决方案

1 个答案:

答案 0 :(得分:1)

First Add below three Class 
public class SmsSentObserver extends ContentObserver {

    private static final String TAG = "SMSTRACKER";
    private static final Uri STATUS_URI = Uri.parse("content://sms");

    private Context mContext;

    public SmsSentObserver(Handler handler, Context ctx) {
        super(handler);
        mContext = ctx;
    }

    public boolean deliverSelfNotifications() {
        return true;
    }

    public void onChange(boolean selfChange) {
        try {
            Log.e(TAG, "Notification on SMS observer");
            Cursor sms_sent_cursor = mContext.getContentResolver().query(STATUS_URI, null, null, null, null);
            if (sms_sent_cursor != null) {
                if (sms_sent_cursor.moveToFirst()) {
                    String protocol = sms_sent_cursor.getString(sms_sent_cursor.getColumnIndex("protocol"));
                    Log.e(TAG, "protocol : " + protocol);
                    if(protocol == null) {
                        //String[] colNames = sms_sent_cursor.getColumnNames();
                        int type = sms_sent_cursor.getInt(sms_sent_cursor.getColumnIndex("type"));
                        Log.e(TAG, "SMS Type : " + type);
                        if(type == 2) {
                            Log.e(TAG, "Id : " + sms_sent_cursor.getString(sms_sent_cursor.getColumnIndex("_id")));
                            Log.e(TAG, "Thread Id : " + sms_sent_cursor.getString(sms_sent_cursor.getColumnIndex("thread_id")));
                            Log.e(TAG, "Address : " + sms_sent_cursor.getString(sms_sent_cursor.getColumnIndex("address")));
                            Log.e(TAG, "Person : " + sms_sent_cursor.getString(sms_sent_cursor.getColumnIndex("person")));
                            Log.e(TAG, "Date : " + sms_sent_cursor.getLong(sms_sent_cursor.getColumnIndex("date")));
                            Log.e(TAG, "Read : " + sms_sent_cursor.getString(sms_sent_cursor.getColumnIndex("read")));
                            Log.e(TAG, "Status : " + sms_sent_cursor.getString(sms_sent_cursor.getColumnIndex("status")));
                            Log.e(TAG, "Type : " + sms_sent_cursor.getString(sms_sent_cursor.getColumnIndex("type")));
                            Log.e(TAG, "Rep Path Present : " + sms_sent_cursor.getString(sms_sent_cursor.getColumnIndex("reply_path_present")));
                            Log.e(TAG, "Subject : " + sms_sent_cursor.getString(sms_sent_cursor.getColumnIndex("subject")));
                            Log.e(TAG, "Body : " + sms_sent_cursor.getString(sms_sent_cursor.getColumnIndex("body")));
                            Log.e(TAG, "Err Code : " + sms_sent_cursor.getString(sms_sent_cursor.getColumnIndex("error_code")));

                            Intent intent = new Intent("smsReceiver");
                            intent.putExtra("person", sms_sent_cursor.getString(sms_sent_cursor.getColumnIndex("person")));
                            intent.putExtra("address", sms_sent_cursor.getString(sms_sent_cursor.getColumnIndex("address")));
                            LocalBroadcastManager.getInstance(mContext).sendBroadcast(intent);
                        }
                    }
                }
            }
            else
                Log.e(TAG, "Send Cursor is Empty");
            sms_sent_cursor.close();
        } catch(Exception sggh) {
            Log.e(TAG, "Error on onChange : "+sggh.toString());
        }
        super.onChange(selfChange);
    }//fn onChange

}//End of class SmsSentObserver

public class SMSTrackerActivity extends BroadcastReceiver {

    private Context mContext;
    private Bundle mBundle;
    private Intent mIntent;

    private static final String TAG = "SMSTRACKER";
    private static final Uri STATUS_URI = Uri.parse("content://sms");

    private SmsSentObserver smsSentObserver = null;

    public void onReceive(Context context, Intent intent) {
        try {
            mContext = context;
            mIntent = intent;
            mBundle = intent.getExtras();  
            Log.e(TAG, "Intent Action : "+intent.getAction());
            if (mBundle != null) {
                getSMSDetails();
            }
            else
                Log.e(TAG, "Bundle is Empty!");

            if(smsSentObserver == null){
                smsSentObserver = new SmsSentObserver(new Handler(), mContext);
                mContext.getContentResolver().registerContentObserver(STATUS_URI, true, smsSentObserver);
            }
        } catch(Exception sgh) {
            Log.e(TAG, "Error in Init : "+sgh.toString());
        }
    }//fn onReceive

    private void getSMSDetails(){        
        SmsMessage[] msgs = null;
        try{
            Object[] pdus = (Object[]) mBundle.get("pdus");
            if(pdus != null){
                msgs = new SmsMessage[pdus.length];
                Log.e(TAG, "pdus length : "+pdus.length);
                for(int k=0; k<msgs.length; k++){
                    msgs[k] = SmsMessage.createFromPdu((byte[])pdus[k]);
                    Log.e(TAG, "getDisplayMessageBody : "+msgs[k].getDisplayMessageBody());
                    Log.e(TAG, "getDisplayOriginatingAddress : "+msgs[k].getDisplayOriginatingAddress());
                    Log.e(TAG, "getMessageBody : "+msgs[k].getMessageBody());
                    Log.e(TAG, "getOriginatingAddress : "+msgs[k].getOriginatingAddress());
                    Log.e(TAG, "getProtocolIdentifier : "+msgs[k].getProtocolIdentifier());
                    Log.e(TAG, "getStatus : "+msgs[k].getStatus());
                    Log.e(TAG, "getStatusOnIcc : "+msgs[k].getStatusOnIcc());
                    Log.e(TAG, "getStatusOnSim : "+msgs[k].getStatusOnSim());
                }
            }
        }
        catch(Exception sfgh){
            Log.e(TAG, "Error in getSMSDetails : "+sfgh.toString());
        }
    }//fn getSMSDetails


}//End of class SMSTrackerActivity


public class IncomingSms extends BroadcastReceiver {

    // Get the object of SmsManager


    @Override
    public void onReceive(Context context, Intent intent) {
        // Retrieves a map of extended data from the intent.
        final Bundle bundle = intent.getExtras();

       // Log.i("bundle OnRecive", "" + bundle.toString());
        try {
            if (bundle != null) {
                final Object[] pdusObj = (Object[]) bundle.get("pdus");
                for (int i = 0; i < pdusObj.length; i++) {
                    SmsMessage currentMessage = SmsMessage.createFromPdu((byte[]) pdusObj[i]);
                    String phoneNumber = currentMessage.getDisplayOriginatingAddress();

                    String senderNum = phoneNumber;
                    String message = currentMessage.getDisplayMessageBody();

                   // Log.i("senderNum", "" + senderNum);
                    //Log.i("message", "" + message);
                  //  Log.i("Constant.verifyCode", "" + Constant.verifyCode);
                    String code = message.substring(message.length() - 4, message.length());
                    Log.i("Verification code", code);
                    if(isNumeric(code)) {
                        Constants.verifyCode = code;
                        Constants.Message_Receive = true;
                    }
                    /*if (message.contains(Constant.verifyCode)) {
                        Constant.Message_Receive = true;
                       // Log.i("message", "OnTRue");
                    }*/
                }
            }
        } catch (Exception e) {
            Log.e("SmsReceiver", "Exception smsReceiver" + e);
        }
    }

    private boolean isNumeric(String str){
        try {
            double d = Double.parseDouble(str);
        } catch(NumberFormatException nfe) {
            return false;
        }
        return true;
    }
}

after add this class in AndroidManifest.xml add below service. 

<receiver android:name=".IncomingSms">
            <intent-filter>
                <action android:name="android.provider.Telephony.SMS_RECEIVED" />
            </intent-filter>
        </receiver>

        <receiver
            android:name=".SMSTrackerActivity"
            android:enabled="true">
            <intent-filter android:priority="101">
                <action android:name="android.provider.Telephony.WAP_PUSH_RECEIVED" />
                <data android:mimeType="application/vnd.wap.mms-message" />
            </intent-filter>

            <intent-filter android:priority="101">
                <action android:name="com.android.mms.transaction.MESSAGE_SENT" />
            </intent-filter>
        </receiver>


    also add below uses-permission.
<uses-permission android:name="android.permission.SEND_SMS" />
    <uses-permission android:name="android.permission.READ_SMS" />
    <uses-permission android:name="android.permission.RECEIVE_SMS" />

After perform above step Make Handler and Put below code in Which Activity need to receive SMScode. 

    public Runnable WebserviceRunnable = new Runnable() {
            @Override
            public void run() {
                CheckMessage();
                handler.removeCallbacks(this);
                handler.postDelayed(this, 2000);
            }
        };

        public void CheckMessage() {
            if (Constants.Message_Receive) {
                Constants.Message_Receive = false;
                etVerificationCode.setText(Constants.verifyCode);
                verifyCode();
    //            servicecallVerify(Constant.verifyCode);
            }
        }