Question

this is my full code for my activity that receives message. Is there any other way to extract the longitude and latitude from a received message?

package com.winzoque.android.tracker;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.widget.Toast;

public class SMSReceiver extends BroadcastReceiver
{

@Override
public void onReceive(Context context, Intent intent)
{

//---get the SMS message passed in---

    Bundle bundle = intent.getExtras();
    SmsMessage[] msgs = null;
    String str = "";
    String lat = "";
    String lon = "";
    if (bundle != null)
    {

//---retrieve the 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();
            str += "\n";

//---i used substring code here, but it is not useful for getting longitude and latitude cause the array of longitude and latitude is keep changing as the place change.

this is the part where i need some help or if you have any suggestion that i can use. I thought of using "split" but I dont know have any idea how it works.

            lat = str.substring(0, 11);
            lon = str.substring(12, 23);

        }

//---display the new SMS message---

        Toast.makeText(context, str, Toast.LENGTH_SHORT).show();

//---this part is to send a broadcast intent to update the message received in the activity---

        Intent broadcastIntent = new Intent();
        broadcastIntent.setAction("SMS_RECEIVED_ACTION");
        broadcastIntent.putExtra("sms", lat);
        broadcastIntent.putExtra("sms1", lon);
        context.sendBroadcast(broadcastIntent);

    }
}
}
Was it helpful?

Solution

As a simple example, I'll assume you get the SMS like so: 31.415922;-27.18281. This would be in your String str after you've processed the incoming SMS. (You should get rid of the line: str += "\n";.) Then:

String[] coords = str.split(";");
String lat = coords[0];
String lon = coords[1];

After this, the String lat would contain the value "31.415922", and the String lon would contain "-27.18281".

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top