Pradeep
Pradeep

Reputation: 2528

Broadcast Receiver does not trigger when Mobile Screen Locks

When I install the app everything works fine. I am able to print Message body every time I send a message until I lock mobile screen. After that, the app stops printing incoming messages. I tried many ways to overcome this problem but with no luck. Please help me...

public class SmsReceiveActivity extends Activity{

@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sms);

receiver = new BroadcastReceiver() {

@Override
public void onReceive(Context context, Intent intent) {

if (intent.getAction().equals(SMS_RECEIVED)) {
Object[] pdus = (Object[]) bundle.get("pdus");
final android.telephony.SmsMessage[] messages = new android.telephony.SmsMessage[pdus.length];

for (int i = 0; i < pdus.length; i++) {
    messages[i] = android.telephony.SmsMessage.createFromPdu((byte[]) pdus[i]);
    incomingMsgString += messages[i].getMessageBody().toString();
   }
    // Print Incoming message Body
  }
 }
}        
  getApplication().registerReceiver(receiver, new IntentFilter(SMS_RECEIVED));
 }
}

Upvotes: 4

Views: 1670

Answers (2)

sandy
sandy

Reputation: 3341

Create your broadcast as static inner class and register it in manifest. Try this link. Receiver as inner class in Android

Upvotes: 0

iagreen
iagreen

Reputation: 31996

Per the BroadcastReceiver docs, when you register a receiver with registerReceiver(), "You won't receive intents when paused". If you want a receiver that is independent of your activity, you should implement it as a named class and publish it in your manifest. For example, create a named class with your anonymous BroadcastReceiver,

public class MyReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {

if (intent.getAction().equals(SMS_RECEIVED)) {
Object[] pdus = (Object[]) bundle.get("pdus");
final android.telephony.SmsMessage[] messages = new android.telephony.SmsMessage[pdus.length];

for (int i = 0; i < pdus.length; i++) {
    messages[i] = android.telephony.SmsMessage.createFromPdu((byte[]) pdus[i]);
    incomingMsgString += messages[i].getMessageBody().toString();
   }
    // Print Incoming message Body
  }
 }
} 

And in your manifest add the receiver inside your application tag

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

Then when an SMS message is received your onReceive method will be invoked. There you can package up the information you need and launch an intent to your Activity or Service for further processing.

Upvotes: 4

Related Questions