Getting latitude and longitude using gps every 10 minutes in the background

I get latitude and longitude using the LocationManager and working correctly.

Requirements:

Get latitude and longitude every 10 minutes if the application is close or not.

I am trying to use services, Thread, AlarmManager, etc.

My application works well for 1-2 hours, after which they will not automatically receive latitude and longitude, but my services still work.

If anyone knows, please give me guidance on how to choose latitude and longitude every 10 minutes in the background.

LocationActivity.java

when the user clicks the start button.

 Intent i=new Intent(context, OnAlarmReceiver.class); PendingIntent pi=PendingIntent.getBroadcast(context, 0, i, 0); alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime()+60000,PERIOD,pi); 

OnAlarmReceiver.java

I am starting my services.

 public class OnAlarmReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { context.startService(new Intent(context, MyService.class)); } } 

MyService.java

 @Override public void onStart(Intent intent, int startId) { // super.onStart(intent, startId); new MyTime(mContext); } 

Mytime.java

getting latitude and longitude.

+4
source share
5 answers

I use this method and solve my problem.

 PendingIntent pi=PendingIntent.getBroadcast(context, 0, i, 0); alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), PERIOD , pi); 

I do not know what is right or wrong. But work is for me. Thanks to @Lucifer, @Maya mAku and @piotrpo for your guide.

0
source

your location really will not be stored in the database, because every time your location is updated (via onLocationChanged(Location location))

what you need to do is bring your timer initialization to your OnCreate() method. then declare these variables.

 double lat = location.getLatitude(); double lng = location.getLongitude(); double alt = location.getAltitude(); 

as global and update them in the onLocationChanged(Location location) method. Thus, whenever the timer causes persistence in your database, the lat, lng, alt values ​​will be available and updated depending on your last location.

 //decalred as global variables String curTime; double lat; double lng; double alt; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); LocationManager locationManager; String context = Context.LOCATION_SERVICE; locationManager = (LocationManager)getSystemService(context); Criteria criteria = new Criteria(); criteria.setAccuracy(Criteria.ACCURACY_FINE); criteria.setAltitudeRequired(false); criteria.setBearingRequired(false); criteria.setCostAllowed(true); criteria.setPowerRequirement(Criteria.POWER_LOW); String provider = locationManager.getBestProvider(criteria, true); //Initialize timer Timer timer = new Timer(); timer.schedule(new TimerTask(){ @Override public void run(){ db.execSQL("INSERT INTO location (longitude,latitude,altitude,tgl_buat) VALUES " + "('"+lng+"','"+lat+"','"+alt+"','"+curTime+"')"); db.close(); } }, 10*60*1000, 10*60*1000); updateWithNewLocation(null); locationManager.requestLocationUpdates(provider, (10*60*1000), 10, locationListener); } private final LocationListener locationListener = new LocationListener() { public void onLocationChanged(Location location) { updateWithNewLocation(location); } public void onProviderDisabled(String provider){ updateWithNewLocation(null); } public void onProviderEnabled(String provider){ } public void onStatusChanged(String provider, int status, Bundle extras){ } }; public void updateWithNewLocation(Location location) { if (location != null) { Dbhelper helper = new Dbhelper(this); final SQLiteDatabase db = helper.getWritableDatabase(); long time = System.currentTimeMillis(); SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd kk:mm:ss"); curTime = df.format(time); lat = location.getLatitude(); lng = location.getLongitude(); alt = location.getAltitude(); System.out.println(lat); System.out.println(lng); System.out.println(alt); } } 

ADDED: - and if you draw a path, then you use this code

 /** Called when the activity is first created. */ private List<Overlay> mapOverlays; private Projection projection; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); linearLayout = (LinearLayout) findViewById(R.id.zoomview); mapView = (MapView) findViewById(R.id.mapview); mapView.setBuiltInZoomControls(true); mapOverlays = mapView.getOverlays(); projection = mapView.getProjection(); mapOverlays.add(new MyOverlay()); } @Override protected boolean isRouteDisplayed() { return false; } class MyOverlay extends Overlay{ public MyOverlay(){ } public void draw(Canvas canvas, MapView mapv, boolean shadow){ super.draw(canvas, mapv, shadow); Paint mPaint = new Paint(); mPaint.setDither(true); mPaint.setColor(Color.RED); mPaint.setStyle(Paint.Style.FILL_AND_STROKE); mPaint.setStrokeJoin(Paint.Join.ROUND); mPaint.setStrokeCap(Paint.Cap.ROUND); mPaint.setStrokeWidth(2); GeoPoint gP1 = new GeoPoint(19240000,-99120000); GeoPoint gP2 = new GeoPoint(37423157, -122085008); Point p1 = new Point(); Point p2 = new Point(); Path path = new Path(); projection.toPixels(gP1, p1); projection.toPixels(gP2, p2); path.moveTo(p2.x, p2.y); path.lineTo(p1.x,p1.y); canvas.drawPath(path, mPaint); } 
+1
source

Try this way

instead of this line

 alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime()+60000,PERIOD,pi); 

try my logic

 alarmManager.set(AlarmManager.RTC_WAKEUP, 60 * 1000, pi); 

You can also see a very good example of AlarmManager .

0
source

I do not see any service finalization team, while you are trying to get a position only in the launch team.

Generally speaking, this is a rather difficult problem: 10 minutes suggests using AlarmManager - this is normal, but ... Getting a position sometimes takes much more than 10 minutes. The GPS receiver consumes an extraordinary amount of battery when it tries to get a correction, so there is a chance that in some circumstances the GPS on / off time will consume more battery than leaving it turned on. Think of some “intermittent compression” - combine different location providers to call GPS only when it is really needed (i.e. Time, a rough change of location, etc.).

0
source
 Try By this one : private void doSomethingRepeatedly() { timer.scheduleAtFixedRate( new TimerTask() { public void run() { try{ //Do your work here } catch (Exception e) { // TODO: handle exception } } }, 0, 10000); } 
0
source

All Articles