I am trying to create an application that will trigger a toast message if the phone receives an SMS message containing a string that is stored in the default settings. My problem is that I was having problems getting the toast that appears when receiving SMS. I checked my code for the recipient with the declared string and it works, but when I use the saved option, it does not appear. Here is my sample code:
public class Main extends Activity{ private static final int RESULT_SETTINGS = 1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); display(); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.action_settings: Intent i = new Intent(this, Settings.class); startActivityForResult(i, RESULT_SETTINGS); break; } return true; } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); switch (requestCode) { case RESULT_SETTINGS: display(); break; } } private void display(){ TextView displayv = (TextView) findViewById(R.id.mysettings); SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
And here is the receiver
public class WakeSMS extends BroadcastReceiver{ @Override public void onReceive(Context context, Intent intent){ SharedPreferences sharedPrefs = context.getSharedPreferences("sharedPrefs", context.MODE_PRIVATE); String trigger=sharedPrefs.getString("smsstr","NULL"); Bundle bundle = intent.getExtras(); SmsMessage[] msgs = null; String str= "SMS from"; if(bundle != null){ Object[] pdus =(Object[])bundle.get("pdus"); msgs=new SmsMessage[pdus.length]; for (int i = 0; i<msgs.length; i++){ msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]); if(i==0){ str+= msgs[i].getOriginatingAddress(); str+=": "; } str+=msgs[i].getMessageBody().toString(); } if(str.contains(trigger)){ Toast.makeText(context, str, Toast.LENGTH_LONG).show(); } } }}
In my main action, I can get my code to display prefs, but in the receiver it cannot call a toast. Is there something I'm doing wrong? (My receiver is called WakeSMS because it should trigger an alarm in the future, but for now I just want it to trigger a toast for testing)
Edit: I have a feeling that the way I declared my preferences in my code may be turned off, but I donβt understand what Iβm doing wrong, since the setting values ββcan be displayed in the main action, but cannot be used in the receiver.
source share