Keep recent SMS received in TextView - java

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 (e.g):
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);

Related

If message contains a text then use the answer (Android Studio)

If the message received have text "1" then show in-app message "Da" (already done part with show app)
If the message received doesn't have text "1" then don't show the app.
MainActivity:
public class MainActivity extends AppCompatActivity {
/* Button msg; */
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/* In beta mode
PreferenceManager.setDefaultValues(this, R.xml.preferences, true); */
setContentView(R.layout.activity_main);
Bundle extras = getIntent().getExtras();
if (extras != null) {
String address = extras.getString("MessageNumber");
String message = extras.getString("Message");
TextView addressField = (TextView) findViewById(R.id.address);
TextView messageField = (TextView) findViewById(R.id.message);
addressField.setText("ALERT From : " + address);
messageField.setText("ALERT Type : " + message);
}
/* msg = (Button)findViewById(R.id.btn_msg);
msg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
}
});*/
SimpleSMSReciver class
public class SimpleSmsReciever extends BroadcastReceiver {
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]);
// Start Application's MainActivty activity
Intent smsIntent=new Intent(context,MainActivity.class);
smsIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
smsIntent.putExtra("MessageNumber", messages.getOriginatingAddress());
smsIntent.putExtra("Message", messages.getMessageBody());
context.startActivity(smsIntent);
// Get the Sender Message : messages.getMessageBody()
// Get the SenderNumber : messages.getOriginatingAddress()
Toast.makeText(context, "Message Received From :"+messages.getOriginatingAddress()+"\n"+ messages.getMessageBody(), Toast.LENGTH_LONG).show();
}
If the message received doesn't have text "1" then don't show the app.
if(!extras.getString("Message").equals("1"))finish();

How to pass data from Receiver to Activity using interface?

I'm trying to pass the data from the brodcast receiver to the activity to display it on the view using an interface, but, it's not working.Here are my files,MainActivity.java
public class MainActivity extends AppCompatActivity implements OtpPassing {
private TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public void onReceive(String msg) {
Toast.makeText(this, "o" + msg, Toast.LENGTH_SHORT).show();
textView = (TextView) findViewById(R.id.textView);
textView.setText("OTP: " + msg);
}
}
OtpPassing.java
public interface OtpPassing {
public void onReceive(String msg);
}
Receiver.java
public class Receiver extends BroadcastReceiver {
// Get the object of SmsManager
final SmsManager sms = SmsManager.getDefault();
public void onReceive(Context context, Intent intent) {
// Retrieves a map of extended data from the intent.
final Bundle bundle = intent.getExtras();
try {
if (bundle != null) {
final Object[] pdusObj = (Object[]) bundle.get("pdus");
for (int i = 0; i < pdusObj.length; i++) {
SmsMessage currentMessage = SmsMessage.createFromPdu((byte[]) pdusObj[i]);
String phoneNumber = currentMessage.getDisplayOriginatingAddress();
String senderNum = phoneNumber;
String message = currentMessage.getDisplayMessageBody();
Log.i("SmsReceiver", "senderNum: " + senderNum + "; message: " + message);
String otp = getOtp(message);
Toast.makeText(context, otp, Toast.LENGTH_LONG).show(); //This is working fine
OtpPassing otpPassing = new MainActivity();
otpPassing.onReceive(otp); //This is not working
} // end for loop
} // bundle is null
} catch (Exception e) {
Log.e("SmsReceiver", "Exception smsReceiver" +e);
}
}
private String getOtp(String message) {
String otp = null;
int index = message.indexOf("otp:");
if(index != -1){
int start = index + 5;
otp = message.substring(start, start+4);
}
return otp;
}
}
The receiver is woking(it's displaying the message on a Toast) but why is displaying the message on the screen via MainActivity not working?
You can create a broadcast receiver as a data member of your activity. You register for it in onCreate and unregister in onDestroy (or onStart and onStop).
That way the receiver has a reference to the parent activity and you can do whatever.
public class MainActivity extends AppCompatActivity implements OtpPassing {
private TextView textView;
BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
//Access the parent activity as follows
MainActivity.this.textView.setText("...");
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//instantiate and register the receiver
setContentView(R.layout.activity_main);
}
#Override
protected void onDestroy() {
// Unregister the receiver here
super.onDestroy();
}
Here better way (I suppose) would be to use Android Intents
in your receiver, something like this
Intent intent = new Intent(context,MainActivity.class);
intent.putExtra(.....);
startactivity(intent);
now in your MainActivity, override onNewIntent(). Here check for the 'extras' you had passed from the receiver.
Please note, this might result in having multiple MainActivities running in your phone if your "older" MainActivity was not killed by the time this intent was passed via receiver. To overcome this, use 'singleTop' or similar flags in your Manifest file

Notification will not open Activity

I have an application where the user may send recipes to others with the application.
Right now, the app is able to send the notification, however, when the notification is clicked, it does not open the intended activity (SmsViewActivity) it simply closes the drawer.
Here is the code for the SmsViewActivity:
public class SmsViewActivity extends Activity {
private static final String TAG = "SmsViewActivity";
private static final String SMS_FOOD = "food_recieved";
private FoodJSONSerializer mSerializer;
public Button mSaveButton, mDismissButton;
public int mNotificationId;
public String message;
private EditText mTitleField;
private CheckBox mImperialCheckBox;
private CheckBox mMetricCheckBox;
private EditText mServingsField;
private EditText mDirectionsField;
private Spinner mMetricSpinner;
private Spinner mImperialSpinner;
Food mFood;
private String msg;
private Activity mActivity;
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
mActivity = this;
setContentView(R.layout.sms_view);
mSaveButton = (Button) findViewById(R.id.save_button_sms);
mDismissButton = (Button) findViewById(R.id.dismiss_button_sms);
this.msg = getIntent().getStringExtra("message");
try {
JSONObject jsonRecipe = new JSONObject(this.msg);
this.mFood = new Food(jsonRecipe);
Log.i(TAG, "Food = " + mFood);
} catch (JSONException e) {
e.printStackTrace();
}
mNotificationId = getIntent().getIntExtra("notificationid", 0);
if (mNotificationId == 0) {
Log.e(TAG, "Could not retrieve notification ID.");
Toast.makeText(this, "A fatal error has occurred in SMS viewer.",
Toast.LENGTH_LONG).show();
finish();
}
String ns = Context.NOTIFICATION_SERVICE;
NotificationManager notificationMgr = (NotificationManager) getSystemService(ns);
notificationMgr.cancel(mNotificationId);
this.mTitleField = (EditText) findViewById(R.id.food_title_sms);
this.mTitleField.setText(mFood.getTitle());
this.mServingsField = (EditText) findViewById(R.id.food_servings_sms);
this.mServingsField.setText(Integer.toString(mFood.getServings()));
this.mDirectionsField = (EditText) findViewById(R.id.directions_text_sms);
this.mDirectionsField.setText(mFood.getDirections());
this.mSaveButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
FoodStorage.get(mActivity).addFood(mFood);
finish();
}
});
this.mDismissButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
backToList();
finish();
}
});
}
public void backToList() {
Intent i = new Intent(this, FoodListFragment.class);
startActivity(i);
}
}
Also here is the receiver Activity:
#Override
public void onReceive(Context context, Intent intent) {
mContext = context;
Bundle bundle = intent.getExtras();
Map<String, String> msgTexts = new LinkedHashMap<String, String>();
if (bundle != null){
Object[] pdus = (Object[]) bundle.get("pdus");
for (Object pdu : pdus) {
SmsMessage message = SmsMessage.createFromPdu((byte[]) pdu);
String incomingMsg = message.getMessageBody();
String originatingNumber = message.getOriginatingAddress();
Log.i(TAG, "Rcvd: from " + originatingNumber + " Msg: " + incomingMsg);
msgTexts.put(originatingNumber, incomingMsg);
smsMessage = incomingMsg;
}
}
processMessages(msgTexts, mNextNotificationId);
}
public void processMessages( Map<String, String> msgTexts, int notificationId ){
for (Entry<String, String> entry : msgTexts.entrySet()) {
Log.i(TAG, "Processing message: " + entry.getValue());
Intent notificationIntent = new Intent(mContext, SmsViewActivity.class);
notificationIntent.putExtra("message", entry.getValue());
notificationIntent.putExtra("sender", entry.getKey());
notificationIntent.putExtra("notificationid", notificationId);
PendingIntent resultPendingIntent = PendingIntent.getActivity(mContext, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder = new NotificationCompat.Builder(mContext)
.setSmallIcon(R.drawable.ic_launcher)
.setTicker("Recipe Received")
.setContentTitle("Recipe Received")
.setContentIntent(resultPendingIntent)
.setContentText("from " + entry.getKey())
.setWhen(System.currentTimeMillis());
NotificationManager notificationMgr = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
notificationMgr.notify(notificationId++, mBuilder.build());
}
}
Try changing the intent flag to:
PendingIntent.FLAG_CANCEL_CURRENT
Otherwise it just updates the existing intent. It should be possible to have an onNewIntent handler in your activity, but I found this works more reliably.

app crashes when intent passes variable to another activity

i am making a app that tracks the user and tracks another user which in theory would be an animal.
my app goes like this, you register a username and pass then when this is done the user can log into the map by reentering the correct username and password. This is where the issues begin.
upon creation of the screen the map loads with the users current location and auto sends a sms to the "animals" phone to request gps details, this then sends back 2 sms messages, 1 containing the gps information. i have a SmsReceiver class which reads this information and extracts the longitude and latitude data, converts it into a double then passes it to the map activity to be converted into a lnglat variable and displayed on the google map with a marker. Now the issue i am having is that it can take several minutes for the sms to return with the gps information, when this is done and the intent is used to send the coordinates to the map page a button must be clicked so that the longitude and latitude are combined into the AnimalCoordinate and the marker is shown, however because og the time gap its imposible to press the button at the same time the sms is retrieved and it causes a crash as the data is being sent from the smsreceiver class to nothing on the other side, and if i take the intent out of the onclick method the same thing happens but in reverse, the map runs the intent but the informaion is not there yet and it crashes.
any help would be greatly appreciated as this has been a nightmare.
i am also sorry if i overcomplicated the explanation, i wanted to ake sure it was explained as best i could.
the code is below for the two classes.
Map class
public class MainScreen extends FragmentActivity implements LocationListener {
private GoogleMap map;
private LocationManager locationManager;
private String provider;
final Context context = this;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_screen);
map = ((SupportMapFragment)getSupportFragmentManager().
findFragmentById(R.id.map)).getMap();
LocationManager service = (LocationManager) getSystemService(LOCATION_SERVICE);
boolean enabledGPS = service
.isProviderEnabled(LocationManager.GPS_PROVIDER);
boolean enabledWiFi = service
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
// Check if enabled and if not send user to the GSP settings
if (!enabledGPS) {
Toast.makeText(this, "GPS signal not found", Toast.LENGTH_LONG).show();
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// Define the criteria how to select the locatioin provider -> use
// default
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);
// Initialize the location fields
if (location != null) {
Toast.makeText(this, "Selected Provider " + provider,
Toast.LENGTH_SHORT).show();
onLocationChanged(location);
} else {
//do something
}
// Sets the map type to be "hybrid"
map.setMapType(GoogleMap.MAP_TYPE_HYBRID);
Bundle b = getIntent().getExtras();
double lat = location.getLatitude();
double lng = location.getLongitude();
Toast.makeText(this, "Location " + lat+","+lng,
Toast.LENGTH_LONG).show();
LatLng Usercoordinate = new LatLng(lat, lng);
Marker User = map.addMarker(new MarkerOptions()
.position(Usercoordinate)
.title("You are here")
.icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_launcher)));
//Move the camera instantly to user with a zoom of 15.
map.moveCamera(CameraUpdateFactory.newLatLngZoom(Usercoordinate, 15));
// Zoom in, animating the camera.
map.animateCamera(CameraUpdateFactory.zoomTo(18), 2000, null);
//Sends sms to 'animal phone'
String phoneNo = "***********";
String sms = "GPSLocation";
try {
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(phoneNo, null, sms, null, null);
Toast.makeText(getApplicationContext(), "SMS Sent!",
Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(getApplicationContext(),
"SMS faild, please try again later!",
Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
public void map_help(View view) {
//method for the help button
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
context);
// set title
alertDialogBuilder.setTitle("Help");
// set dialog message
alertDialogBuilder
.setMessage("Click the 'Pet' button to display the pets location." +
"This can take a few minutes to retrieve.")
.setCancelable(false)
.setPositiveButton("ok",new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog,int id) {
// if this button is clicked, close
// current activity
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
};
public void Find_Pet(View view)
{
//String phoneNo = "07516909014";
// String sms = "GPSLocation";
// try {
// SmsManager smsManager = SmsManager.getDefault();
//smsManager.sendTextMessage(phoneNo, null, sms, null, null);
//Toast.makeText(getApplicationContext(), "SMS Sent!",
// Toast.LENGTH_LONG).show();
// } catch (Exception e) {
// Toast.makeText(getApplicationContext(),
// "SMS faild, please try again later!",
//Toast.LENGTH_LONG).show();
// e.printStackTrace();
//}
}
public void Show_Pet(View view)
{
//gets coordinates from SmsReceiver
Bundle b = getIntent().getExtras();
double AnimalLat = b.getDouble("key");
Bundle d = getIntent().getExtras();
double AnimalLon = d.getDouble("key1");
LatLng Animalcoordinate = new LatLng(AnimalLat, AnimalLon);
//adds pets marker on map
Marker Animal = map.addMarker(new MarkerOptions()
.position(Animalcoordinate)
.title("Your pet is here")
.icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_launcher)));
}
/* Request updates at startup */
#Override
protected void onResume() {
super.onResume();
locationManager.requestLocationUpdates(provider, 400, 1, this);
}
/* Remove the locationlistener updates when Activity is paused */
#Override
protected void onPause() {
super.onPause();
locationManager.removeUpdates(this);
}
#Override
public void onLocationChanged(Location location) {
}
#Override
public void onProviderDisabled(String provider) {
Toast.makeText(this, "Enabled new provider " + provider,
Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderEnabled(String provider) {
Toast.makeText(this, "Disabled provider " + provider,
Toast.LENGTH_SHORT).show();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
SmsReceiver class
public class SmsReceiver extends BroadcastReceiver
{
String lat = null;
String lon = null;
String message = null;
final SmsReceiver context = this;
#Override
public void onReceive(Context context, Intent intent)
{
//---get the SMS message passed in---
Bundle bundle = intent.getExtras();
SmsMessage[] msgs = null;
String str = "";
if (bundle != null)
{
//---retrieve the SMS message received---
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]);
str += msgs[i].getMessageBody().toString();
}}
message = str.toString();
String[] test = message.split("");
char[] test2 = test[1].toCharArray();
//if the first character of the sms is C then read gps information
if (test2[0] == 'C' || test2[0] =='c')
{
lat = message.substring(45, 56);
lon = message.substring(67, 78);
double AnimalLat=Double.parseDouble(lat);
double AnimalLon=Double.parseDouble(lon);
//Pass coordinates to MainScreen
Intent a = new Intent(getApplicationContext(), MainScreen.class);
Bundle b = new Bundle();
b.putDouble("key", AnimalLat);
a.putExtras(b);
startActivity(a);
Intent c = new Intent(getApplicationContext(), MainScreen.class);
Bundle d = new Bundle();
d.putDouble("key1", AnimalLon);
c.putExtras(d);
startActivity(c);
}else {
}
}
private void startActivity(Intent a) {
// TODO Auto-generated method stub
}
private Context getApplicationContext() {
// TODO Auto-generated method stub
return null;
}}
I also want to apologize for the layout of the code, this is the first time i have pasted code on this site.
Thanks again.
To be honest, I'm not sure which Button you are talking. The only one I saw was in the AlertDialog unless I missed something. Anyway, you can disable your Button until whatever data has a value or you can do nothing in the onClick() if it is null
//inside your Button
if (data != null)
{
...do stuff in here
}
If you need more clarification then please indicate in the code the data you are talking about and the Button but I think you get the idea.

How to extract phone number from the selected contact?

public class ImportContactsActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button pickContact = (Button) findViewById(R.id.contacts);
pickContact.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
startActivityForResult(intent, 1);
}
});
}
public void onActivityResult(int reqCode, int resultCode, Intent data) {
super.onActivityResult(reqCode, resultCode, data);
switch (reqCode) {
case (1) :
if (resultCode == Activity.RESULT_OK) {
Uri contactData = data.getData();
Cursor c = managedQuery(contactData, null, null, null, null);
if (c.moveToFirst()) {
String name = c.getString(c.getColumnIndexOrThrow(People.NAME));
TextView contactView = (TextView) findViewById(R.id.contactView);
contactView.setText(name.toString());
}
}
break;
}
}
I am developing an Android apps and I am importing the phone contacts into my apps, after user clicks on the selected contact, the contact will be shown in a TextView and the phone number will be stored in the sharedpreferences... May I know how to achieve it? Thanks
Have you tried?
Uri contactData = data.getData();
Cursor cursor = managedQuery(contactData, null, null, null, null);
cursor.moveToFirst();
String name = cursor.getString(cursor.getColumnIndexOrThrow(People.NAME));
String number = cursor.getString(cursor.getColumnIndexOrThrow(People.NUMBER));
String email = cursor.getString(cursor.getColumnIndexOrThrow(People.PRIMARY_EMAIL_ID));
contactName.setText(name);
contactNumber.setText(number);
contactEmail.setText(email);
For store in SharedPreferences..
// We need an Editor object to make preference changes.
// All objects are from android.context.Context
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("phonenumber", number);
// Commit the edits!
editor.commit();
The above code is just for understanding..
A possible duplicate of the following link
get contact info from android contact picker
Refer to the above link. It has been answered in detail.

Categories