越来越纬度和经度使用GPS在后台的android每10分钟(getting latitude and

2019-07-22 20:05发布

我做了使用经度和纬度获得LocationManager和工作正确。

需求:

获得纬度和经度每隔10纪录,如应用程序关闭或没有。

我试着服务,螺纹,AlarmManager等。

我的应用程序是为工作1-2小时,然后好后自动得不到纬度和经度,但我的服务仍在运行。

如果再有任何人知道,请给我指导线如何获取经度和纬度的背景每10分。

LocationActivity.java

当用户点击启动按钮。

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

我是开始我的服务。

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

越来越经度和纬度。

Answer 1:

您的位置会因为您的每一次位置更新真的不保存在数据库中(via onLocationChanged(Location location))

你应该做的是把你的timer初始化在你OnCreate()方法。 然后声明这些变量。

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

全球和有他们在更新onLocationChanged(Location location)方法。 这样一来,每当计时器在你的数据库调用持久性的纬度,经度,ALT值将可用并根据您最新的位置更新。

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

    } 

  }

新增: - 如果你绘制路径,那么你使用此代码

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


Answer 2:

试试这个方法,

而不是这条线

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

试试我的逻辑,

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

您还可以看到的一个很好的例子AlarmManager 。



Answer 3:

我没有看到任何服务最终确定命令,而你正在试图让只在启动命令的位置。

一般来说 - 这是相当复杂的问题,10分钟内提出AlarmManager的使用 - 这是好的,但...获取位置有时持续时间远远超过10分钟。 GPS接收机消耗电池,当它试图获得位置固定的数额特别巨大,所以有可能,在某些条件下切换GPS /关闭定期会比离开它打开消耗更多的电池。 考虑到一些“loosy压缩” - 结合不同的位置提供调用GPS真的只在需要时(即时间,粗略位置改变等)



Answer 4:

我使用这种方式,解决我的问题。

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

我不知道这是我的权利或wrong.but工作。 感谢@路西法,@玛雅马库和@piotrpo你的理念为指导。



Answer 5:

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


文章来源: getting latitude and longitude using gps every 10 minute in background android