【问题标题】:getting latitude and longitude using gps every 10 minute in background android在后台android中每10分钟使用gps获取纬度和经度
【发布时间】:2013-03-23 04:40:10
【问题描述】:

我已经完成使用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

获取纬度和经度。

【问题讨论】:

  • Harshid,你能上传你的代码吗?
  • @Lucifer 查看我的更新代码

标签: android google-maps google-maps-api-3 gps


【解决方案1】:

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

您应该做的是将您的timerinitialization 带入您的OnCreate() 方法中。然后声明这些变量。

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

作为全局并在onLocationChanged(Location location)method 中更新它们。这样,每当计时器调用数据库中的持久性时,lat、lng、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);
}

【讨论】:

    【解决方案2】:

    试试这个方法,

    代替这一行

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

    试试我的逻辑,

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

    你也可以看到AlarmManager的一个很好的例子。

    【讨论】:

    • 为什么 pendingIntent 不在后台调用。
    【解决方案3】:

    我没有看到任何服务完成命令,而您试图仅在启动命令上获得位置。

    一般来说 - 这是一个相当复杂的问题: 10 分钟的时间建议使用 AlarmManager - 没关系,但是...... 获得位置有时会持续超过 10 分钟。 GPS 接收器在尝试定位时会消耗大量电池,因此在某些情况下,周期性地打开/关闭 GPS 会比打开时消耗更多的电池。 考虑一些“松散压缩”——结合不同的位置提供者,仅在真正需要时调用 GPS(即时间、粗略位置改变等)

    【讨论】:

      【解决方案4】:

      我正在使用这种方式并解决我的问题。

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

      我不知道这是对还是错。但为我工作。 感谢 @Lucifer、@Maya mAku 和 @piotrpo 的指导。

      【讨论】:

        【解决方案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);
                             }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多