Search code examples
androidbroadcastreceiver

Passing data from Activity to BroadcastReceiver


I have an BroadcastReceiver which add prefix to phone number of outgoing call and prefix is add by user.

Are there any way to pass Prefix (String variable) to BroadcastReceiver?

I mean after my app is kill, this BroadcastReceiver still working with Prefix that user wanted to add.

This is my code for register BroadcastReceiver

PackageManager pm  = getApplicationContext().getPackageManager();
ComponentName componentName = new componentName(MyActivity.this,MyBroadcastReceiver.class);
pm.setComponentEnabledSetting(componentName,PackageManager.COMPONENT_ENABLED_STATE_ENABLED,PackageManager.DONT_KILL_APP);

Please help me regarding this.


Solution

  • Through intent you can do like this -

    Passing Class -

    Intent i = new Intent(passing.this, received.class);
    Bundle b = new Bundle();
    b.putString("keyvalue", "yourprefixvalue");
    i.putExtras(b);
    startActivity(i);
    

    Received Class -

    In your broadcast receiver class contains onReceive method and having arguments intent. So that it can be used to get the result value from bundle.

    @Override
    public void onReceive(Context context, Intent intent) 
    {
        String result = intent.getString("keyvalue");
        // your method
    }
    

    Try this out. I've passed some values to my BroadcastReceiver class like this.