Amruth Pillai
Amruth Pillai

Reputation: 1693

Receive SMS Messages only when Activity in Running

I am building an Android application that receives SMS messages and displays them from a particular gateway/sender.

The problem is, if I declare the receiver in the AndroidManifest file, it keeps receiving messages from everyone and at all times, even when the app is paused/closed. This causes a force crash of the app every time I receive a SMS message when not on the app.

This is my code in ReceieveMessage.java

package com.phoenix.omnisurf;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;

public class ReceiveMessage extends BroadcastReceiver {

private static final String SMS_RECEIVED = "android.provider.Telephony.SMS_RECEIVED";
public static String messageBody = "";

@Override
public void onReceive(Context context, Intent intent) {
    final Bundle bundle = intent.getExtras();
    if (bundle != null) {

        messageBody = "";

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

        for (int i = 0; i < pdus.length; i++) {
            SmsMessage messageHandler = SmsMessage.createFromPdu((byte[]) pdus[i]);
            messageBody += messageHandler.getDisplayMessageBody();
        }

        SurfActivity.mThis.messageContainer.setText(messageBody);
    }
}
}

I also have the following receiver registered on my Manifest:

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

    <!-- Message Receiver -->
    <receiver android:name=".ReceiveMessage">
        <intent-filter>
            <action android:name="android.provider.Telephony.SMS_RECEIVED" />
        </intent-filter>
    </receiver>

How do I create a Broadcast Receiver that is on only when the particular activity is open or when the app is running?

Upvotes: 1

Views: 917

Answers (2)

Bracadabra
Bracadabra

Reputation: 3659

You can register your receiver dynamically:

@Override
protected void onResume() {
    super.onResume();
    final IntentFilter filter = new IntentFilter("android.provider.Telephony.SMS_RECEIVED");
    registerReceiver(mBroadcastReceiver, filter);
}

@Override
protected void onPause() {
    super.onPause();
    unregisterReceiver(mBroadcastReceiver);
}

Upvotes: 2

kalyan pvs
kalyan pvs

Reputation: 14590

Just check whether your Activity is in foreground or not

Add this to your Activity private static boolean isInForeground;

onResume(){
 super.onResume();
 isInForground = true;
}

onPause(){
 super.onPause();
 isInForground = false;
}

And in your Receiver class check like

 if(SurfActivity.isInForeground){
   SurfActivity.mThis.messageContainer.setText(messageBody);
}

Upvotes: 2

Related Questions