Reputation: 1082
I am having a problem while passing a string from my main activity to my broadcast receiver when the app is not currently open on the screen.
When the MainActivity class is created the intent filter returns the correct information through the broadcast receiver but as soon as the user goes to the homescreen on their phone the broadcast receiver starts returning "null" for the toast when the receiver is triggered offscreen.
1. New Intent
Intent home_page = new Intent(newIntent.this,MainActivity.class);
ownAddress = ""+customInput.getText().toString();
home_page.putExtra("session_number", ""+ownAddress);
startActivity(home_page);
2. MainActivity.java:
public class MainActivity extends DroidGap {
SmsReceiver mAppReceiver = new SmsReceiver();
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle bundle = getIntent().getExtras();
final String ownAddress = bundle.getString("session_number");
registerReceiver(mAppReceiver, new IntentFilter("SmsReceiver"));
Intent intent = new Intent("SmsReceiver");
intent.putExtra("passAddress", ownAddress);
sendBroadcast(intent);
}
}
3. SmsReceiver.java:
public class SmsReceiver extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
Toast showme = Toast.makeText(context,"Number: "+intent.getExtras().get("passAddress"),Toast.LENGTH_LONG);
showme.show();
}
}
Is there anyway to pass the string through to the broadcast receiver while the app is only running in the background or regardless of when the MainActivity class is created?
Upvotes: 0
Views: 1123
Reputation: 2691
I may be wrong here but, logically, the reason why "the broadcast receiver starts returning "null" for the toast when the receiver is triggered offscreen" is because the context that you pass to the onReceive constructor is destroyed when the user goes to the homescreen.
I guess one solution for passing the string would be to create a public static string variable in MainActivity which is used to store the string value you want to pass. Then all you have to do is access this string statically in your BroadcastReceiver.
Upvotes: 0