Search code examples
javaandroiddynamicbroadcastreceiver

BroadcastReceiver object only uses initial values, why?


Hi I'm trying to run a code which has one activity and a BroadcastReceiver which runs when new message comes and yes it's run clearly but I have a problem with BroadcastReceiver object !

It's part of MainActivity CLASS :

public class MainActivity extends FragmentActivity {


   private IncomingSms checkAndDo; //=> OBJECT 

   @Override
   protected void onCreate(Bundle savedInstanceState) {

       super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_main);


       checkAndDo= new IncomingSms(); 
       checkAndDo.setProgramState(210); // program state is a variable
       checkAndDo.getProgramState(this); // Toast output  : " >>>210  "

       ....

But problem starts when a new message comes and onReceived() called ! IncommingSms class :

public class IncomingSms extends BroadcastReceiver {

private int programState=110; // Which state we are ?  110=> white / 111=> off / 210=>black ...     


public void onReceive(Context context, Intent intent) {

    final Bundle bundle = intent.getExtras();


    this.getProgramState(context);  
     // This method called again but  toast output is : ">>>110" 
     // which is initial value !?

    AND .... 

  }



public void setProgramState(int status) {

    this.programState=status;

}


public void getProgramState( Context context) {


     Toast.makeText(context, ">>>"+this.programState , Toast.LENGTH_LONG).show();

}  

question : I'm not sure why it happens but onReceive() uses only the initial value which is so bad . ANY Idea?


Solution

  • this.getProgramState(context);  
     // This method called again but  toast output is : ">>>110" 
     // which is initial value !?
    

    You met that problem because you registered your BroadcastReceiver in the manifest. So Android will create a new BroadcastReceiver and pass the sms broadcast to it.

    If you would like to get the state you set in your program, you must register your BroadcastReceiver in your Activity.

    IntentFilter filter = new IntentFilter("android.provider.Telephony.SMS_RECEIVED");
    registerReceiver(checkAndDo, filter);