1

I wanna send location via sms from Broadcast Receiver. The code doesn't work at all in determining my location. Anyone can help me to solve my problem?

SmsRemoteController

public class SmsRemoteController extends BroadcastReceiver {
    private static final int MODE_WORLD_READABLE = 1;
    private String smsFirstCode;
    private SharedPreferences myPrefs;
    private Context contexts;
    private String sendingNumber = "";


    @Override
    public void onReceive(Context context, Intent intent) {
        contexts = context;
        myPrefs = context.getSharedPreferences("myPrefs", MODE_WORLD_READABLE);
        String smsMode = myPrefs.getString("state", "not");
        AppLocationService appLocationService;
        appLocationService = new AppLocationService(SmsRemoteController.class);

        if (smsMode.equals("ON")) {

            Bundle bundle = intent.getExtras();
            SmsMessage[] msgs = null;
            String smsBody = "";
            if (bundle != null) {
                Object[] pdus = (Object[]) bundle.get("pdus");
                msgs = new SmsMessage[pdus.length];
                for (int i = 0; i < pdus.length; i++) {
                    msgs[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
                    sendingNumber += msgs[i].getOriginatingAddress();
                    smsBody = msgs[i].getMessageBody().toString();
                }

                // Toast.makeText(contexts, "number"+sendingNumber+"..body"+smsBody.toLowerCase(), Toast.LENGTH_SHORT).show();


                if (smsBody.equals("locate")) {


                    Location nwLocation = appLocationService.getLocation(LocationManager.NETWORK_PROVIDER);

                    if (nwLocation != null) {
                        double latitude = nwLocation.getLatitude();
                        double longitude = nwLocation.getLongitude();
                        Toast.makeText(contexts, "Mobile Location (NW): \nLatitude: " + latitude + "\nLongitude: " + longitude,
                                Toast.LENGTH_LONG).show();

                    } else {
                        Location gpsLocation = appLocationService.getLocation(LocationManager.GPS_PROVIDER);

                        if (gpsLocation != null) {
                            double latitude = gpsLocation.getLatitude();
                            double longitude = gpsLocation.getLongitude();
                            Toast.makeText(contexts, "Mobile Location (GPS): \nLatitude: " + latitude
                                            + "\nLongitude: " + longitude,
                                    Toast.LENGTH_LONG).show();
                        }

                    }


                }
                //abortBroadcast();
            }// end of onReceive()


        }

    } // end of the class
}

AppLocationService

public class AppLocationService extends Service implements LocationListener {

    protected LocationManager locationManager;
    Location location;

    private static final long MIN_DISTANCE_FOR_UPDATE = 10;
    private static final long MIN_TIME_FOR_UPDATE = 1000 * 60 * 2;

    public AppLocationService(Context context) {
        locationManager = (LocationManager) context.getSystemService(LOCATION_SERVICE);
    }

    public Location getLocation(String provider) {
        if (locationManager.isProviderEnabled(provider)) {
            locationManager.requestLocationUpdates(provider,MIN_TIME_FOR_UPDATE, MIN_DISTANCE_FOR_UPDATE, this);
            if (locationManager != null) {
                location = locationManager.getLastKnownLocation(provider);
                return location;
            }
        }
        return null;
    }

    @Override
    public void onLocationChanged(Location location) {
    }

    @Override
    public void onProviderDisabled(String provider) {
    }

    @Override
    public void onProviderEnabled(String provider) {
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
    }

    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }

}
chridam
  • 100,957
  • 23
  • 236
  • 235

1 Answers1

2

The way you are calling service is not preferred way of using Service, We never creates object of service in the BoradcastReceiver So you can register for a Location receiver and based on the updated value you receive you can show the Toast of perform required operation. I have updated below one of the possible solution for your requirement.

Also I would still prefer to start a service from the Broadcast receiver for getting the location as we should not be heavy operation on the BroadcastReceiver,

public class SmsRemoteController extends BroadcastReceiver {
    private static final int MODE_WORLD_READABLE = 1;
    private String smsFirstCode;
    private SharedPreferences myPrefs;
    private Context contexts;
    private String sendingNumber = "";
    public static final int MIN_TIME_REQUEST = 5 * 1000;
    public static final String ACTION_REFRESH_SCHEDULE_ALARM =
                    "org.mabna.order.ACTION_REFRESH_SCHEDULE_ALARM";
    private static Context _context;
    private static LocationManager locationManager;


    private static LocationListener locationListener = new LocationListener() {

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras){
            try {
                String strStatus = "";
                switch (status) {
                case GpsStatus.GPS_EVENT_FIRST_FIX:
                    strStatus = "GPS_EVENT_FIRST_FIX";
                    break;
                case GpsStatus.GPS_EVENT_SATELLITE_STATUS:
                    strStatus = "GPS_EVENT_SATELLITE_STATUS";
                    break;
                case GpsStatus.GPS_EVENT_STARTED:
                    strStatus = "GPS_EVENT_STARTED";
                    break;
                case GpsStatus.GPS_EVENT_STOPPED:
                    strStatus = "GPS_EVENT_STOPPED";
                    break;
                default:
                    strStatus = String.valueOf(status);
                    break;
                }
                Toast.makeText(_context, "Status: " + strStatus,
                        Toast.LENGTH_SHORT).show();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onProviderEnabled(String provider) {}

        @Override
        public void onProviderDisabled(String provider) {}

        @Override
        public void onLocationChanged(Location location) {
            try {
                Toast.makeText(_context, "***new location***",
                        Toast.LENGTH_SHORT).show();
            } catch (Exception e) {
            }
        }
    };


    @Override
    public void onReceive(Context context, Intent intent) {
        contexts = context;
        myPrefs = context.getSharedPreferences("myPrefs", MODE_WORLD_READABLE);
        String smsMode = myPrefs.getString("state", "not");

        if (smsMode.equals("ON")) {

            Bundle bundle = intent.getExtras();
            SmsMessage[] msgs = null;
            String smsBody = "";
            if (bundle != null) {
                Object[] pdus = (Object[]) bundle.get("pdus");
                msgs = new SmsMessage[pdus.length];
                for (int i = 0; i < pdus.length; i++) {
                    msgs[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
                    sendingNumber += msgs[i].getOriginatingAddress();
                    smsBody = msgs[i].getMessageBody().toString();
                }

                // Toast.makeText(contexts,
                // "number"+sendingNumber+"..body"+smsBody.toLowerCase(),
                // Toast.LENGTH_SHORT).show();

                if (smsBody.equals("locate")) {

                    _context = context;
                    locationManager = (LocationManager) context
                            .getSystemService(Context.LOCATION_SERVICE);
                    if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
                        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
                                MIN_TIME_REQUEST, 5, locationListener);
                        Location gotLoc = locationManager
                                .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                        double latitude = gotLoc.getLatitude();
                        double longitude = gotLoc.getLongitude();
                        Toast.makeText(contexts, "Mobile Location (NW): \nLatitude: " + latitude + "\nLongitude: " + longitude,
                                Toast.LENGTH_LONG).show();
                    } else {
                        Toast t = Toast.makeText(context, "please turn on GPS",
                                Toast.LENGTH_LONG);
                        t.setGravity(Gravity.CENTER, 0, 0);
                        t.show();
                        Intent settinsIntent = new Intent(
                                android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                        settinsIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        _context.startActivity(settinsIntent);
                    }
                }
                // abortBroadcast();
            }// end of onReceive()

        }

    } // end of the class
}
Pratik Goyal
  • 294
  • 1
  • 9