demo
demo

Reputation: 712

Alarm Manager not firing every 5 second

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);
        }
    }
}

Upvotes: 0

Views: 1464

Answers (1)

Nick Cardoso
Nick Cardoso

Reputation: 21733

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);

Upvotes: 2

Related Questions