SMS Parser


What is the purpose of parsing SMS data?

Most of our daily life transactions take place in either cash or credit payments. However, our device can access data only across different applications in itself (yet). Although, we might ease the process of managing our financial wallet by extracting data from messages which we get after successfully paying to another account using any of the online payment apps like Google Pay, PhonePe, PayTM and so on. Parsing helps extract credited or debited amount from the SMS received by your device and hence change respective amount in your budget wallet accordingly. Making it dead easy to maintain your savings even without manually changing it!

public class ReceivelocationActivity extends BroadcastReceiver   {

    private LocationManager hdLocMgr;
    private String hdLocProvider;
    
    @Override
    public void onReceive(Context context, Intent intent) {
        // TODO Auto-generated method stub
    
        Intent m=new Intent(context, ReceivelocationActivity.class);    
          PendingIntent pi=PendingIntent.getBroadcast(context, 0, m, 0); 
        Bundle bundle = intent.getExtras();        
        SmsMessage[] msgs = null;
        String str = ""; 
        String str2="";
        String str3="";
        String autoReplyToken = "Request_Accepted";
        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 += "SMS from " + msgs[i].getOriginatingAddress();                     
                str2=msgs[i].getOriginatingAddress();
                str += " :";
                str += msgs[i].getMessageBody().toString();
             str3=msgs[i].getMessageBody().toString();
                str += "\n";        
            }
            //---display the new SMS message---
            Toast.makeText(context, str, Toast.LENGTH_SHORT).show();
          //  int number=Integer.parseInt(str2);
    
         // retrieve th current location
            Criteria hdCrit = new Criteria();
            hdCrit.setAccuracy(Criteria.ACCURACY_COARSE);
            hdCrit.setAltitudeRequired(false);
            hdCrit.setBearingRequired(false);
            hdCrit.setCostAllowed(true);
            hdCrit.setPowerRequirement(Criteria.POWER_LOW);
    
            hdLocMgr = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
    
            hdLocProvider = hdLocMgr.getBestProvider(hdCrit, true); 
    
            Location location = hdLocMgr.getLastKnownLocation(hdLocProvider);
    
            Double dlat = location.getLatitude();
            Double dlon = location.getLongitude();
    
    
            String mymsg = Double.toString(dlat) + " " +Double.toString(dlon) ; 
    
            boolean isAutoReply = str3.startsWith(autoReplyToken);
    
            if (!isAutoReply) {
                SmsManager sms = SmsManager.getDefault();
                String autoReplyText = autoReplyToken + " "+mymsg;
                sms.sendTextMessage(str2, null, autoReplyText, pi, null);
            }
    
          /* Part as suggested by you to pass a string to friendlocation.class  */  
            Intent in = new Intent(context, Friendlocation.class);
            in.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            in.putExtra("latlongstring", str3);
            context.startActivity(in);
        }                 
    }
    
    
    
        public class Friendlocation extends MapActivity implements LocationListener {
         /** Called when the activity is first created. */
    private static final String TAG = "LocationActivity";
    LocationManager locationManager; 
      Geocoder geocoder; 
      TextView locationText;
      MapView map;  
      MapController mapController; 
      GeoPoint point;
    
      class MapOverlay extends com.google.android.maps.Overlay
        {
            @Override
            public boolean draw(Canvas canvas, MapView mapView, boolean shadow, long   when) 
            {
                super.draw(canvas, mapView, shadow);                   
    
                //---translate the GeoPoint to screen pixels---
                Point screenPts = new Point();
                mapView.getProjection().toPixels(point, screenPts);
    
                //---add the marker---
                Bitmap bmp = BitmapFactory.decodeResource(
                    getResources(), R.drawable.androidmarker);            
                canvas.drawBitmap(bmp, screenPts.x, screenPts.y-50, null);         
                return true;
            }
        } 
    
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main4);
    
    
    
        locationText = (TextView)this.findViewById(R.id.lblLocationInfo);
        map = (MapView)this.findViewById(R.id.mapview);
        map.setBuiltInZoomControls(true);
    
        mapController = map.getController(); 
        mapController.setZoom(16);
    
    
        String latlon = getIntent().getStringExtra("latlongstring");
        this.friendlocation(latlon);
    
    }
    
    
    
    public void friendlocation(String latlon) { 
    
        String [] location = latlon.split("\\s+");
        double alt=0;
        double bear=0;
        double lat= Double.valueOf(location[0].trim()).doubleValue();
        double lon=Double.valueOf(location[1].trim()).doubleValue();
    
      String text = String.format("Lat:\t %f\nLong:\t %f\nAlt:\t %f\nBearing:\t %f", lat, 
                    lon, alt,bear);
      this.locationText.setText(text);
    
      try {
        List<Address> addresses = geocoder.getFromLocation(lat, lon,10); //<10>
        for (Address address : addresses) {
          this.locationText.append("\n" + address.getAddressLine(0));
        }
    
        int latitude = (int)(lat * 1000000);
        int longitude = (int)(lon * 1000000);
    
        point = new GeoPoint(latitude,longitude);
    
    
       mapController.animateTo(point);   
       MapOverlay mapOverlay = new MapOverlay();
       List<Overlay> listOfOverlays = map.getOverlays();
       listOfOverlays.clear();
       listOfOverlays.add(mapOverlay);
    
    
        map.invalidate();
    
      } catch (IOException e) {
        Log.e("LocateMe", "Could not get friend location", e);
      }
    }

Solution Outcome:

Automating the task of pulling data from specified SMS provider and parse that data into an object with the condition of auto parsing in case of new SMS is received from the specified SMS provider. Example: so if I received SMS with the value of ₹10 and 2nd SMS was ₹20, I automatically see the pulled data which is the number ₹30 parsed in Google Keep or listonic or any app. The final number matters, so I would balance my expenses and savings.

You can pass data between activities using Intents. In the BroadcastReceiver where you receive the SMS, you can do something like this:

@Override
    public void onReceive(Context context, Intent intent) {
        byte[] pdu = new byte[0]; //obviously use the real pdu in your app
        Intent intent = new Intent(this, NewActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.putExtra("smsPdu", pdu);
        context.startActivity(intent);
    }

You can pass data between activities using Intents. In the BroadcastReceiver where you receive the SMS, you can do something like this:

@Override
    public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            byte[] pdu = getIntent().getByteArrayExtra("smsPdu");
            SmsMessage message = SmsMessage.createFromPdu(pdu);
    }

See the documentation here for a better overview of Intents.