I want to fetch the latest text SMS which has been sent to a particular phoneNumber, and check whether the text SMS contains a substring "Greetings from " + appname, if no such SMS has been received, then it should return "no msg"

My code:

    @SuppressLint("NewApi")
    public String getAllSms(String phoneNumber) {
        phoneNumber = "+91"+phoneNumber; //tried removing the ISD but it doesn't do anything
        String lstsms = "no msg";
        ContentResolver cr = getContentResolver();

        // Get today's date in milliseconds
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        long todayMillis = calendar.getTimeInMillis();

        // Query for SMS messages from the specified phone number received today or earlier
        String selection = Telephony.Sms.Inbox.ADDRESS + " = ? AND " +
                Telephony.Sms.Inbox.DATE + " <= ?";
        String[] selectionArgs = {phoneNumber, String.valueOf(todayMillis)};

        Cursor cursor = cr.query(
                Telephony.Sms.Inbox.CONTENT_URI,
                new String[]{Telephony.Sms.Inbox.BODY},
                selection,
                selectionArgs,
                Telephony.Sms.Inbox.DEFAULT_SORT_ORDER
        );

        if (cursor != null) {
            Log.d("SMS Query", "Cursor count: " + cursor.getCount());

            if (cursor.moveToFirst()) {
                int bodyIndex = cursor.getColumnIndexOrThrow(Telephony.Sms.Inbox.BODY);

                do {
                    String body = cursor.getString(bodyIndex);
                    Log.d("SMS Query", "Body: " + body);

                    if (body.contains("Greetings from " + appname)) {
                        lstsms = body;
                        break;
                    }
                } while (cursor.moveToNext());

                cursor.close();
            } else {
                Log.d("SMS Query", "Cursor is empty");
            }
        } else {
            Log.d("SMS Query", "Cursor is null");
        }
        return lstsms;
    }

The function keeps returning no msg, even when there is an SMS received by the phoneNumber containing Greetings from + appname. Moreover, logging the cursor.getCount() keeps showing 0 and cursor.moveToFirst() keeps showing false.

Where am I going wrong? Please guide me.

I have also added and requested the runtime permission into my manifest:

<uses-permission android:name="android.permission.READ_SMS" />
0

There are 0 best solutions below