0

I am working with a SMS listener, code below:

public class SMSReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        EventEntry entry = ((MyApplication)context.getApplicationContext()).getCurrent();
        System.out.println("Received message: " + smsMessage[0].getMessageBody() + " - SILENCE IS " + ((entry != null) ? "ON" : "OFF"));
    }
}

And following modification to AndroidManifest

<application
    android:name="MyApplication" ...

In another part of my code (in a BroadcastReceiver for AlarmManager), I have

public void onReceive(Context context, Intent intent) {
    ((MyApplication).context.getApplicationContext()).setCurrent("TESTING");
}

However, when I run the application and send a sample text, I get the following debug messages:

09-15 15:07:30.974: I/System.out(21625): DEBUG!!!!!! Setting current event to TESTING
09-15 15:07:54.399: I/System.out(21605): DEBUG!!!!!! Getting current event: null

Any ideas why my application contexts are out of sync?

Thanks!

Jin
  • 6,055
  • 2
  • 39
  • 72

2 Answers2

0

I can give you one alternative solution of this, Just you can override onCreate() method in your MyApplication class.

class MyApplication extends Application {
private static MyApplication singleTon;

public MyApplication getInstance(){
return singleTon;
}

@Override
public void onCreate() {
singleTon = this;
}


...... Here your remaining code....

}

Now you can access the instance of this class and then call getApplicationContex();

 (MyApplication.getInstance().getapplicationContext()).getCurrent();

Hope it can helpful to you...:)

Vishesh Chandra
  • 6,951
  • 6
  • 35
  • 38
0

Your application can be killed at any time, if the system is facing memory shortage. So static variables or singletons will get reinitialized. Maybe that is the reason it is null.

You should use SharedPreferences instead of storing it in application class

nandeesh
  • 24,740
  • 6
  • 69
  • 79