简体   繁体   中英

Keep recent SMS received in TextView

I'm trying to keep the recent received SMS to TextView, but when i close the app then open it again the TextView returns to empty is there a way to keep the recent received SMS in TextView even if its closes the app

MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Bundle extras = getIntent().getExtras();

    TextView addressField  = (TextView) findViewById(R.id.tvAddress);
    TextView messageField = (TextView) findViewById(R.id.tvMessage);

    if(extras != null){

        String address = extras.getString("MessageNumber");
        String message = extras.getString("Message");
        addressField.setText(address);
        messageField.setText(message);

    }

}

SimpleSmsReceiver.java

private static final String TAG = "Message recieved";

@Override
public void onReceive(Context context, Intent intent) {
    Bundle pudsBundle = intent.getExtras();
    Object[] pdus = (Object[]) pudsBundle.get("pdus");
    SmsMessage messages = SmsMessage.createFromPdu((byte[]) pdus[0]);
    Intent smsIntent=new Intent(context,MainActivity.class);
    smsIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    String sender = messages.getDisplayOriginatingAddress();
    smsIntent.putExtra("MessageNumber", sender);
    smsIntent.putExtra("Message", messages.getMessageBody());
    if(PhoneNumberUtils.compare("12345", sender) | PhoneNumberUtils.compare("123456", sender) ) {
        context.startActivity(smsIntent);
        Toast.makeText(context, "SMS Received From Device" , Toast.LENGTH_LONG).show();
    }
}

Use Shared Preferences in your SimpleSmsReceiver class since you're only passing data to the MainActivity using Intent but this won't save the data for the next time user opens the app.

In your SimpleSmsReceiver (eg):

SharedPreferences.Editor editor = getSharedPreferences("YourKey", MODE_PRIVATE).edit();
editor.putString("MessageNumber", sender);
editor.putString("Message", messages.getMessageBody())
editor.apply();

Then to retrieve those values inside your MainActivity :

SharedPreferences prefs = getSharedPreferences("YourKey", MODE_PRIVATE);
String messageNumber = prefs.getString("MessageNumber", null);
String message = prefs.getString("Message", null);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM