Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Aborting/Cancelling Broadcasts

What I want: I want to be the first to receive the Sms Broadcast and I want to cancel the broadcast if SMS is of my interest only, so that The broadcast doesn't reach any other app/receiver (Default messaging app etc.). What I know is:

  • SmsDisptacher.java uses orderedBroadcasts that can be can canceled/aborted.

What I don't know is:

  • If orderedBrodcasts can be canceled for other apps/receivers i.e other than yourself.

what I have tried for being the first to receive the Broadcast:

  • intent-filter android:priority="1000"

What i have tried for canceling broadcast already:

  • AbortBroadcast();
  • broadcastReceiver.setResultCode(RESULT_CANCELED)
  • clearAbortBroadcast()
like image 899
hassanadnan Avatar asked Mar 04 '11 07:03

hassanadnan


1 Answers

It is certainly possible. Register your receiver in your manifest like this:

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

In your receiver's onReceive method write:

@Override
public void onReceive(Context context, Intent intent) {
    if (intent.getAction().equals(SMS_RECEIVED)) {
        //do your stuff
        abortBroadcast();
    }
}

Remember to set the permission to receive sms messages in the manifest like this:

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

Without the correct permission set it will fail silently with the following logcat message:

07-13 12:54:13.208: WARN/ActivityManager(201): Permission Denial: receiving Intent { act=android.provider.Telephony.SMS_RECEIVED (has extras) } to com.mypackage requires android.permission.RECEIVE_SMS due to sender com.android.phone (uid 1001)

Finally, it is possible that another application has registered a receiver with an even higher priority than yours, and that it therefore receives the broadcast before you cancel it. So if all else fails, try experimenting with higher priority values.

like image 154
Marmoy Avatar answered Oct 09 '22 11:10

Marmoy