0

I want to send my current location to server for every 5 or 10 seconds. But for me its Alarm Manager firing randomly.i already tried google suggestions.

I tried this are all link:

1.setRepeating() of AlarmManager repeats after 1 minute no matter what the time is set (5 seconds in this case, API 18+)

2.enteAndroid Alarm manager is repeating after 5sec

Activity.java

public class AlarmActivity extends AppCompatActivity {


    Button button;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_alarm);


        button = (Button) findViewById(R.id.button1);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                //startService(new Intent(AlarmActivity.this, CurrentLocation_Tracking.class));
                startAlert();
            }
        });
    }
    public void startAlert() {
        EditText text = (EditText) findViewById(R.id.time);
        int i = Integer.parseInt(text.getText().toString());
        Intent intent = new Intent(this, MyBroadcastReceiver.class);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(
                this.getApplicationContext(), 234324243, intent, 0);
        AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);

       /* alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()
                + (i * 1000), pendingIntent);*/

        alarmManager.setInexactRepeating(AlarmManager.RTC, System.currentTimeMillis(), (i * 1000), pendingIntent);
        Toast.makeText(this, "Alarm set in " + i + " seconds", Toast.LENGTH_LONG).show();
    }
}

BroadcastReceiver

public class MyBroadcastReceiver extends BroadcastReceiver {
    MediaPlayer mp;
    @Override
    public void onReceive(Context context, Intent intent) {

        context.startService(new Intent(context, CurrentLocation_Tracking.class));

        mp= MediaPlayer.create(context, R.raw.notification);
        mp.start();
        Toast.makeText(context, "Alarm....", Toast.LENGTH_LONG).show();
    }
}

Service class

public class CurrentLocation_Tracking extends Service {

    private static final String TAG = "BOOMBOOMTESTGPS";
    private LocationManager mLocationManager = null;
    private static final int LOCATION_INTERVAL = 1000; // 5 seconds
    private static final float LOCATION_DISTANCE = 1f;  //30 meters
    LocationListener[] mLocationListeners;
    SharedPreferences sp;
    SharedPreferences.Editor editor;

    String status_currenttrack = "";
    private Context mContext;

    private class LocationListener implements android.location.LocationListener {
        Location mLastLocation;

        public LocationListener(String provider) {
            Log.e(TAG, "LocationListener " + provider);
            mLastLocation = new Location(provider);
        }

        @Override
        public void onLocationChanged(Location location) {
            Log.e(TAG, "onLocationChanged: " + location);

            Log.d("currentlocation..", "" + location.getLongitude() + " " + location.getLatitude());

             //Sent_LatLngs_currentpostion("" + location.getLatitude(), "" + location.getLongitude());

            Toast.makeText(CurrentLocation_Tracking.this, "latlongvale" + location.getLatitude() + "" + location.getLongitude(), Toast.LENGTH_LONG).show();
            mLastLocation.set(location);

            mLocationManager.removeUpdates(LocationListener.this);
        }

        @Override
        public void onProviderDisabled(String provider) {
            Log.e(TAG, "onProviderDisabled: " + provider);
        }

        @Override
        public void onProviderEnabled(String provider) {
            Log.e(TAG, "onProviderEnabled: " + provider);
        }

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {
            Log.e(TAG, "onStatusChanged: " + provider);
        }
    }


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

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d(TAG, "onStartCommand");
        super.onStartCommand(intent, flags, startId);
       // stopSelf();

         mLocationListeners = new LocationListener[]{
                new LocationListener(LocationManager.GPS_PROVIDER),
                new LocationListener(LocationManager.NETWORK_PROVIDER)
        };

        initializeLocationManager();

        try {
            mLocationManager.requestLocationUpdates(
                    LocationManager.GPS_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE,
                    mLocationListeners[0]);
        } catch (java.lang.SecurityException ex) {
            Log.d("failvalue", "fail to request location update, ignore", ex);
        } catch (IllegalArgumentException ex) {
            Log.d("gpstages", "gps provider does not exist " + ex.getMessage());
        }

        return START_STICKY;
    }

    @Override
    public void onCreate() {
        Log.d(TAG, "onCreate");
        mContext=this;
    }

    @Override
    public void onDestroy() {
        Log.d("Destroy", "onDestroy");
        super.onDestroy();
        if (mLocationManager != null) {
            for (int i = 0; i < mLocationListeners.length; i++) {
                try {

                    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                        // TODO: Consider calling
                        //    ActivityCompat#requestPermissions
                        // here to request the missing permissions, and then overriding
                        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                        //                                          int[] grantResults)
                        // to handle the case where the user grants the permission. See the documentation
                        // for ActivityCompat#requestPermissions for more details.
                        return;
                    }
                    mLocationManager.removeUpdates(mLocationListeners[i]);
                } catch (Exception ex) {
                    Log.i(TAG, "fail to remove location listners, ignore", ex);
                }
            }
        }
    }

    private void initializeLocationManager() {
        Log.d("initialize", "initializeLocationManager");
        if (mLocationManager == null) {
            mLocationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
        }
    }
}
Cœur
  • 37,241
  • 25
  • 195
  • 267
demo
  • 672
  • 3
  • 9
  • 34
  • Why down vote guys,give me suggestion i will correct it. – demo Sep 11 '17 at 12:36
  • This is where you are fireing your alarm right: alarmManager.setInexactRepeating(AlarmManager.RTC, System.currentTimeMillis(), (i * 1000), pendingIntent); Toast.makeText(this, "Alarm set in " + i + " seconds", Toast.LENGTH_LONG).show(); – Anders Sørensen Sep 11 '17 at 12:40
  • @ Anders Kink `i` value i am passing by Editext as a 5 – demo Sep 11 '17 at 12:40
  • @ Anders Kink yes you are correct – demo Sep 11 '17 at 12:42
  • 1
    instead of setInexactRepeating try : setRepeating – Anders Sørensen Sep 11 '17 at 12:43
  • 1
    Checking location every 5 seconds will kill your users battery - Just a note - if you release this now, Android O won't let you continue like this. Also `private static final int LOCATION_INTERVAL = 1000; // 5 seconds` is actually 1 second and the AlarmManager will not fire so often – Nick Cardoso Sep 11 '17 at 12:47
  • setRepeating is not working @AndersKink – demo Sep 11 '17 at 12:49
  • @ Nick Cardoso so what i have to change,you are saying that i need to change as `LOCATION_INTERVAL = 5000` i am correct. – demo Sep 11 '17 at 12:51
  • @NickCardoso Ok then what is alternative solution please suggest me sir. – demo Sep 11 '17 at 12:53
  • Well actually it looks like you never use the constant anyway, as if it was code coped from elsewhere – Nick Cardoso Sep 11 '17 at 12:55
  • I chaged `private static final int LOCATION_INTERVAL = 5000;` then also not working properly. – demo Sep 11 '17 at 12:55
  • @Mariyappan please don't use `AlarmManager`. I am sure you won't like apps using your device battery right too much? So, instead use `GCMNetworkManager` or `Firebase Job Dispatcher`. Also when you try to get location every certain seconds, you will probably end of getting same location. Instead you should request location updates with interval, accuracy and displacement. And do whatever you desire when you receive location update. You could also make your service a `Foreground Service`, so that the system will not kill it. – Milan Sep 11 '17 at 13:40
  • @Milan Thank you very much,can you provide some reference linke please sir,.. – demo Sep 11 '17 at 14:48

1 Answers1

2

You should just need to change to

alarmManager.setRepeating(AlarmManager.RTC, System.currentTimeMillis(), (i * 1000), pendingIntent);

But Note the Javadoc:

for timing operations (ticks, timeouts, etc) it is easier and much more efficient to use Handler

and

as of API 19, all repeating alarms are inexact If your application needs precise delivery times then it must use one-time exact alarms

So it may be better to use:

alarmManager.set(AlarmManager.RTC, System.currentTimeMillis() + (i * 1000), pendingIntent);

Or the following if you target API 19:

alarmManager.setExact(AlarmManager.RTC, System.currentTimeMillis() + (i * 1000), pendingIntent);
Nick Cardoso
  • 20,807
  • 14
  • 73
  • 124