LA_
LA_

Reputation: 20409

How to pass parameters to the BroadcastReceiver declared in AndroidManifest?

I have a SMSReceiver declared in AndroidManifest:

<receiver android:name="com.example.SMSReceiver"
          android:enabled="false">
    <intent-filter android:priority="999" >
        <action android:name="android.provider.Telephony.SMS_RECEIVED" />
    </intent-filter>
</receiver>

This is disabled by default and I enable it, when needed:

ComponentName component = new ComponentName(context, SMSReceiver.class);
PackageManager pm = context.getPackageManager();
pm.setComponentEnabledSetting(
        component,
        PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
        PackageManager.DONT_KILL_APP);

How could I pass some parameter to SMSReceiver in this case? I use SharedPreferences currently, but it doesn't look good since I don't take care about Activity closure etc.

Upvotes: 4

Views: 1523

Answers (2)

CommonsWare
CommonsWare

Reputation: 1006869

How could I pass some parameter to SMSReceiver in this case?

In the abstract, you send it a broadcast. Just because you enable a component does not mean that you instantiate a component.

However, since manifest-registered BroadcastReceivers do not live past the end of onReceive(), I have no idea what you think that passing "some parameter" to such a receiver would accomplish.

Moreover, since onReceive() is called on the main application thread, you should not be doing anything significant in the BroadcastReceiver in the first place.

Upvotes: 1

Gilad Haimov
Gilad Haimov

Reputation: 5857

I know of no way of passing parameters via ComponentName.


What I do when a receiver needs configuration is to create a ReceiverParam singleton, and have the receiver read it before execution:


class SMSReceiverParams {
     private String param1;
     private String param2;

     private static SMSReceiverParams instance;

     public static SMSReceiverParams getInstance() { ... }


    public void setParam1() { .. } 

    public String getParam1() { .. } 

}


Now, from my app init code (say an Activity) - perform the configuration:

SMSReceiverParams.getInstance().setParam1(...);
SMSReceiverParams.getInstance().setParam2(...);


And at receiver end - read the params before onReceive() execution

class SMSReceiver {

         void onReceive() {
                 SMSReceiverParams params = SMSReceiverParams.getInstance(); // <--------
                 // and use them
          }
}

Upvotes: 0

Related Questions