Search code examples
androidsqlitegpsproximity

Can we increment or dynamically change the name of flag variable in android?


I'm developing an App to send Proximity alerts via SMS. In which it sends SMS to numbers in SQLite Database. Latitude and Longitude values also stored in database. Now my code sends whenever the phone enters appropriate LatLng it sends SMS to the number saved with the LatLng. Now I want to change the code to send SMS to all numbers only once before 12 noon. And I want to send one SMS to all numbers once when they enter their proximity after 12 noon. i.e. one sms before 12 and one sms after 12 for each number not more than that. I used the following code to try that by initializing a Flag Variable. After send the SMS the flag value changes and prevents from sending sms again. But I faced a problem it sends SMS once to numbers in first proximity. Failed to send all the next proximities. My code is

Code for Adding Proximity Alerts

 try {
            databaseHelper = new DatabaseHelper(this);
            db = databaseHelper.getReadableDatabase();

            Cursor cursor = db.rawQuery("select rowid _id,*from latLngTable", null);
            go = cursor.moveToFirst();

            while (cursor.isAfterLast() != true) {
                String strLat = cursor.getString(cursor.getColumnIndex("latitude"));
                String strLng = cursor.getString(cursor.getColumnIndex("longitude"));
                String strStopName = cursor.getString(cursor.getColumnIndex("Stop_Name"));
                float strRadius = cursor.getFloat(cursor.getColumnIndex("radius"));
                String mobileNo = cursor.getString(cursor.getColumnIndex("Phone_NO"));

                double dLat = Double.parseDouble(strLat);
                double dLng = Double.parseDouble(strLng);

                if (strRadius==0.0){
                    radius=150;
                }else {
                    radius=strRadius;
                }

                LocationManager locationManager2 = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
                locationManager2.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
                String proximitys = "com.realtech.latlngrecorder" + n;
                Intent i = new Intent(proximitys);
                i.putExtra("phone", mobileNo);
                i.putExtra("stopName", strStopName);
                sendBroadcast(i);

                PendingIntent pi = PendingIntent.getBroadcast(this, n, i, PendingIntent.FLAG_CANCEL_CURRENT);
                locationManager2.addProximityAlert(dLat, dLng, radius, -1, pi);
                IntentFilter filter = new IntentFilter(proximitys);
                registerReceiver(new ProximityIntentReceiver(), filter);
                Log.w("Alert Added", "Alert Added to All Locations");
                n++;
                cursor.moveToNext();
            }
        } catch (SQLiteException e) {
            e.printStackTrace();
            Toast.makeText(MainPage.this, "Failed to add Proximity Alert", Toast.LENGTH_SHORT).show();
        }

Proximity Alert BroadcastReceiver is

public class ProximityIntentReceiver extends BroadcastReceiver {

String smsNo;
String lat,lng,stopingName,lat1,lng1;
Double latitude,longitude,latitude1,longitude1;
DecimalFormat dFormat,dFormat1;
boolean flag=true;
SharedPreferences preferences;

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

    smsNo=intent.getStringExtra("phone");
    stopingName=intent.getStringExtra("stopName");

    preferences=context.getSharedPreferences("flagTest",Context.MODE_PRIVATE);
    if (!preferences.contains("flag")){
        SharedPreferences.Editor editor=preferences.edit();
        editor.putBoolean("flag",true);
        editor.commit();
        editor.clear();
    }

    final String proximityKey= LocationManager.KEY_PROXIMITY_ENTERING;
    Boolean entering=intent.getBooleanExtra(proximityKey,false);
    if (entering){
        Log.d(getClass().getSimpleName(), "entering");

        Calendar morningStart= Calendar.getInstance();
        Calendar morningEnd = Calendar.getInstance();
        setTime(morningStart,7);
        setTime(morningEnd, 10);

        Calendar eveningStart = Calendar.getInstance();
        Calendar eveningEnd = Calendar.getInstance();

        setTime(eveningStart, 15);
        setTime(eveningEnd, 19);

        Calendar currentTime = Calendar.getInstance();
        Calendar limitTime = Calendar.getInstance();
        setTime(limitTime,12);

        boolean flagVar=preferences.getBoolean("flag",true);

        if (currentTime.after(limitTime)&&flag==flagVar){

            try {

                final SmsManager smsManager = SmsManager.getDefault();
                String[] numbers = smsNo.split(",");
                for (final String number : numbers) {

                    final LocationManager locationManager=(LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
                    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, new LocationListener() {
                        @Override
                        public void onLocationChanged(Location location) {
                            dFormat=new DecimalFormat("#.####");
                            latitude=location.getLatitude();
                            longitude=location.getLongitude();
                            lat=dFormat.format(latitude);
                            lng=dFormat.format(longitude);

                            smsManager.sendTextMessage(number, null, "Stop:" + stopingName + "\n\nSchool Van will reach you shortly.\n\nhttp://maps.google.com/maps?q=" + lat + "," + lng, null, null);

                            SharedPreferences.Editor editor=preferences.edit();
                            editor.putBoolean("flag",false);
                            editor.commit();
                            editor.clear();

                            locationManager.removeUpdates(this);
                        }

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

                        }

                        @Override
                        public void onProviderEnabled(String provider) {

                        }

                        @Override
                        public void onProviderDisabled(String provider) {

                        }
                    });

                }

            }catch (Exception e){
                Toast.makeText(context,"No mobile Number Registered",Toast.LENGTH_SHORT).show();
            }
        }else if (currentTime.before(limitTime)&&flag==preferences.getBoolean("flag",false)){

            try {

                final SmsManager smsManager = SmsManager.getDefault();
                String[] numbers = smsNo.split(",");
                for (final String number : numbers) {

                    final LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
                    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, new LocationListener() {
                        @Override
                        public void onLocationChanged(Location location) {
                            dFormat1 = new DecimalFormat("#.####");
                            latitude1 = location.getLatitude();
                            longitude1 = location.getLongitude();
                            lat1 = dFormat1.format(latitude1);
                            lng1 = dFormat1.format(longitude1);

                            smsManager.sendTextMessage(number, null, "Stop:" + stopingName + "\n\nSchool Van will reach you shortly.\n\nhttp://maps.google.com/maps?q=" + lat + "," + lng, null, null);

                            SharedPreferences.Editor editor=preferences.edit();
                            editor.putBoolean("flag",true);
                            editor.commit();
                            editor.clear();

                            locationManager.removeUpdates(this);
                        }

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

                        }

                        @Override
                        public void onProviderEnabled(String provider) {

                        }

                        @Override
                        public void onProviderDisabled(String provider) {

                        }
                    });
                }
            }catch (Exception e){
                Toast.makeText(context,"No Mobile number registered",Toast.LENGTH_SHORT).show();
            }
        }else{
            Toast.makeText(context,"Time Flag Exception",Toast.LENGTH_SHORT).show();
        }
    }else {
        Log.d(getClass().getSimpleName(), "exiting");
        Toast.makeText(context,"exiting",Toast.LENGTH_SHORT).show();
    }

}

private void setTime(Calendar calendar, int hour) {
    calendar.set(Calendar.HOUR_OF_DAY, hour);
    calendar.set(Calendar.MINUTE, 0);
    calendar.set(Calendar.SECOND, 0);
}

}


Solution

  • I am the developer of Place SMS - an app that auto sends SMS triggered by location. Actually you set the flag to false on the first loop iteration. After which the rest iterations are not executed. Move the code below outside the loop:

    SharedPreferences.Editor editor=preferences.edit();
                                editor.putBoolean("flag",false);
                                editor.commit();
                                editor.clear();