Reputation: 4467
I have an alarm setup and that part works. When the alarm is received I set a String to the message that was saved with the alarm. But when I show this string on the UI its not set.
Here is the first code that show the UI that would show the string:
public class ShowAlm extends Activity {
private static String MessStr="ZZZ";
public static void setMessStr(String messStr) {
MessStr = messStr;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.showalm);
Toast.makeText(this,"Message " + MessStr, Toast.LENGTH_SHORT).show();
}
Then to test it without the Alarm I put a button on another class to call above and everything works as expected:
btnplot.setOnClickListener(new Button.OnClickListener() {
@Override
public void onClick(View v) {
ShowAlm.setMessStr("AAA");
Intent intent1 = new Intent(context, ShowAlm.class);
intent1.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
context.startActivity(intent1);
//TestAlarm();
//Intent intent = new Intent(v.getContext(), AutoComplete4.class);
// startActivity(intent);
}
});
Here is where the problem is, the same code as the button above but in the receiver does not work. The string is not set.
public class AlarmReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
try {
Bundle bundle = intent.getExtras();
String message = bundle.getString("alarm_message");
System.out.println("Message = " + message);
ShowAlm.setMessStr("AAA");
Intent intent1 = new Intent(context, ShowAlm.class);
intent1.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
context.startActivity(intent1);
} catch (Exception e) {
}
}
So when the 2nd code above is show the MessStr is the default value. I also tried had coding "AAA" as the string but that didnt help.
So the end result is the log shows the string is there, but when the UI is shown the string is default.
Ideas?
Upvotes: 0
Views: 186
Reputation: 73484
I assume the problem is that its a static variable. When the Receiver starts the new activity, it may be loading the class again, and the static var will be initialized to "ZZZ". The proper way to do it is to put the String into the Intent Extras.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.showalm);
Intent i = getIntent();
MessStr = i.getStringExtra("alarmMessage", null);
if(MessStr != null) {
Toast.makeText(this,"Message " + MessStr, Toast.LENGTH_SHORT).show();
}
}
public void onReceive(Context context, Intent intent) {
try {
Intent intent1 = new Intent(context, ShowAlm.class);
intent1.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent1.putExtra("alarmMessage", "AAA");
context.startActivity(intent1);
} catch (Exception e) {
}
}
Upvotes: 1