• After 15+ years, we've made a big change: Android Forums is now Early Bird Club. Learn more here.

Please Help! (SMS receiver related)

Hello everyone,

Let me give you a brief explanation of my situation.

I'm a mediocre programer. I only had taken two formal classes in computer programing (in the JAVA language) in my life. And am very new to android (phone) app development. About 4 months ago I decided to develop an app for encrypting sms messages. Now the app is nearly 90% complete, I still have one nagging problem I'm trying to solve:

How can I make the app receive SMS messages in the background when the app is no longer in the foreground?

e.g. Suppose someone has google Crome open in the foreground and is receiving a sms message. I simply want my app to say (perhaps implemented with the "Toast.maketext(...).show()" method), "You have received and encrypted messages from +15555215554".

My app already is able to do this when running in the foreground. But I want to do it in the background. I just don't know what this is called. So I'm uncertain what to google search. So far I've googled "android studio sms receiver" and "android studio sms service" and "android studio receive SMS background", but neither results have helped me. Here are my manifest and broadcast recover classes if that helps:

Here's my manifest code:
Code:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.sendreadsmsexample">

    <uses-permission android:name="android.permission.SEND_SMS" />
    <uses-permission android:name="android.permission.READ_SMS" />
    <uses-permission android:name="android.permission.RECEIVE_SMS" />
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".ManMess"
            android:label="Manage Messages"
            android:parentActivityName=".MainActivity"></activity>
        <activity android:name=".ManKeys"
            android:label="Manage Keys"
            android:parentActivityName=".MainActivity"/>
        <activity android:name=".About"
            android:label="About"
            android:parentActivityName=".MainActivity"/>
        <activity android:name=".MainActivity" android:windowSoftInputMode="adjustPan" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

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

        <service android:name=".MessageService"
            android:enabled="true"/>

    </application>

</manifest>

Here's my SmsBroadcastReceiver:
Code:
package com.example.sendreadsmsexample;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.text.method.ScrollingMovementMethod;
import android.widget.TextView;
import android.widget.Toast;

import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;


public class SmsBroadcastReceiver extends BroadcastReceiver
{
    @Override
    public void onReceive(Context context, Intent intent)
    {
        MainActivity mainActivity = new MainActivity();
        StringManager stringManager = new StringManager();
        MessageLogger messageLogger = new MessageLogger();
        KeyManager keyManager = new KeyManager();

        if(intent.getAction().equals("android.provider.Telephony.SMS_RECEIVED"))
        {
            Bundle bundle = intent.getExtras();
            SmsMessage[] msgs = null;
            String msg_from = "";
            String msgBody = "";

            if (bundle != null)
            {

                try
                {
                    Object[] pdus = (Object[]) bundle.get("pdus");

                    msgs = new SmsMessage[pdus.length];

                    for(int i=0; i<msgs.length; i++)
                    {
                        msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
                        msg_from = msgs[i].getOriginatingAddress();
                        msgBody = msgs[i].getMessageBody();

                        if (MainActivity.mThis != null )
                        {
                            if( stringManager.isKey(msgBody) && keyManager.hasKey(msg_from, context) == false )
                            {
                                Toast.makeText(context,"Recieved key piece: " + stringManager.getKeyNumber(msgBody) + " from " + msg_from + ".", Toast.LENGTH_LONG).show();
                                keyManager.addKeyEntry(msg_from, msgBody, context);
                                if( keyManager.hasKey(msg_from, context) )
                                {
                                    Toast.makeText(context,"A secure link has been established! You can now send encrypted messages to " + msg_from + ".", Toast.LENGTH_LONG).show();
                                }
                            }
                            else
                            {
                                ((TextView) MainActivity.mThis.findViewById(R.id.txtFrom)).setText("Sender: " + msg_from + " | Recieved Message Packet # " + stringManager.getNumber(msgBody));
                                messageLogger.addEntry(msgBody, msg_from, context);

                                if(messageLogger.gotMessageByID(msg_from,stringManager.getNumberID(msgBody),context))
                                {
                                    FileManager fileManager = new FileManager();
                                    MessageHistory messageHistory = new MessageHistory(msg_from, context);
                                    int ID = stringManager.getNumberID(msgBody);
                                    RSAUtil rsa = new RSAUtil();

                                    String text = "";

                                    text = messageLogger.getMessageByID(msg_from, ID, context);
                                    messageHistory.addEntry(text);
                                    String[] entries = messageHistory.getEntries();

                                    for(int j = 0; j < entries.length; j++)
                                    {
                                        try
                                        {
                                            entries[j] = "> " + rsa.decrypt(entries[j], fileManager.getContent("myPrivKey.txt", context)) + "\n";
                                        }
                                        catch (IllegalBlockSizeException e)
                                        {
                                            e.printStackTrace();
                                        }
                                        catch (InvalidKeyException e)
                                        {
                                            e.printStackTrace();
                                        }
                                        catch (BadPaddingException e)
                                        {
                                            e.printStackTrace();
                                        }
                                        catch (NoSuchAlgorithmException e)
                                        {
                                            e.printStackTrace();
                                        }
                                        catch (NoSuchPaddingException e)
                                        {
                                            e.printStackTrace();
                                        }
                                    }
                                    ((TextView) MainActivity.mThis.findViewById(R.id.txtFull)).setMovementMethod(new ScrollingMovementMethod());
                                    ((TextView) MainActivity.mThis.findViewById(R.id.txtFull)).setText(stringManager.unite(entries));
                                }
                            }
                        }
                    }
                }
                catch(Exception e)
                {

                }
            }
        }
    }
}
 
Alright everyone....feel like I'm talking to myself here, but I know there are readers. I Finally found the solution to my problem!

If you want to log and receive notifications of sms messages while your app in the background, you're program would have to read the sms inbox, which every android phone has.

Here's an example of some code which implements the sms inbox.
https://www.androidauthority.com/how-to-create-an-sms-app-721438/
Code:
public class MainActivity extends AppCompatActivity {

   ArrayList<String> smsMessagesList = new ArrayList<>();
   ListView messages;
   ArrayAdapter arrayAdapter;
   private static final int READ_SMS_PERMISSIONS_REQUEST = 1;

   @Override
   protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_main);
       messages = (ListView) findViewById(R.id.messages);
       input = (EditText) findViewById(R.id.input);
       arrayAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, smsMessagesList);
       messages.setAdapter(arrayAdapter);
       if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_SMS)
               != PackageManager.PERMISSION_GRANTED) {
          getPermissionToReadSMS();
       } else {
          refreshSmsInbox();
   }
}
and...
Code:
public void refreshSmsInbox() {
   ContentResolver contentResolver = getContentResolver();
   Cursor smsInboxCursor = contentResolver.query(Uri.parse("content://sms/inbox"), null, null, null, null);
   int indexBody = smsInboxCursor.getColumnIndex("body");
   int indexAddress = smsInboxCursor.getColumnIndex("address");
   if (indexBody < 0 || !smsInboxCursor.moveToFirst()) return;
   arrayAdapter.clear();
   do {
       String str = "SMS From: " + smsInboxCursor.getString(indexAddress) +
                  "\n" + smsInboxCursor.getString(indexBody) + "\n";
       arrayAdapter.add(str);
   } while (smsInboxCursor.moveToNext());
}

That's what the problem was. I didn't know that an sms inbox existed.
 
There are definitely readers - but this one had nothing to offer. Thank you for sharing the solution you found!
 
Back
Top Bottom