0

I want open App when receive SMS. I try to handle this problem using Manifest-declared receivers.

Here is my code

<AndroidManifest.xml>
    
    <receiver
        android:name=".service.SMSReceiver"
        android:enabled="true"
        android:exported="true"
        android:permission="android.permission.BROADCAST_SMS">
        <intent-filter>
            <action android:name="android.provider.Telephony.SMS_RECEIVED" />
        </intent-filter>
    </receiver>
  @Override
public void onReceive(Context context, Intent intent) {

    packageManager = context.getPackageManager();

    if("android.provider.Telephony.SMS_RECEIVED".equals(intent.getAction())) {

        Bundle bundle = intent.getExtras();
        Object[] messages = (Object[]) bundle.get("pdus");
        for (Object pdu : messages)
        {
            SmsMessage message = SmsMessage.createFromPdu((byte[]) pdu);
            if(message == null)
            {
                Log.e(TAG,"message is null");
                break;
            }
            smsSender = message.getDisplayOriginatingAddress();
            if(smsSender.compareTo(number)==0)
            {
                receivedData = new Date(message.getTimestampMillis());

                smsBody = message.getDisplayMessageBody();
                Log.i(TAG, "onReceive: "+smsBody);
                SendToActivity(context,smsSender,smsBody,receivedData);
            }

        }
    }
}
 private void SendToActivity(Context context, String sender, String contents, Date receivedDate) {
    Log.i(TAG, "SendToActivity: TEST ");

    Intent intent = new Intent(context, MainActivity.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK|
            Intent.FLAG_ACTIVITY_SINGLE_TOP|
            Intent.FLAG_ACTIVITY_CLEAR_TOP);

    intent.putExtra("contents",contents);
    context.startActivity(intent);
    Log.i(TAG, "SendToActivity: RUN >>  ");
    
}

this code works only when app is onPause(). I want to work even app is terminated.

Is possible that terminated app open automatically when SMS received at Android 9?

Ali Esmailpor
  • 1,209
  • 3
  • 11
  • 22
siyeon
  • 3
  • 2
  • You might get something from this older post regarding broadcast receivers: https://stackoverflow.com/questions/44149921/broadcast-receiver-not-working-when-app-is-closed/60197247 – CodexNZ Jan 22 '21 at 02:28

1 Answers1

-1

No, you can't do this. There are certain limitations that Android had put on the Broadcast Receivers.

There are certain broadcasts that Apps can't listen to, and it includes the SMS broadcast too.

You can find more about here

There are some broadcasts which your app can listen to when terminated, you can find the list here