我正在尝试将最近收到的SMS保留为TextView,但是当我关闭应用程序然后再次打开它时,TextView返回为空,有一种方法可以将最近收到的SMS保留在TextView中,即使它关闭了该应用程序< / p>
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();
}
}
答案 0 :(得分:1)
在Shared Preferences
类中使用SimpleSmsReceiver
,因为您仅使用MainActivity
将数据传递到Intent
,但这不会为下次用户保存数据打开应用。
在您的SimpleSmsReceiver
中(例如):
SharedPreferences.Editor editor = getSharedPreferences("YourKey", MODE_PRIVATE).edit();
editor.putString("MessageNumber", sender);
editor.putString("Message", messages.getMessageBody())
editor.apply();
然后在MainActivity
中检索这些值:
SharedPreferences prefs = getSharedPreferences("YourKey", MODE_PRIVATE);
String messageNumber = prefs.getString("MessageNumber", null);
String message = prefs.getString("Message", null);