5

緯度と経度の取得とLocationManager適切な作業が完了しました。

要件:

アプリケーションが近くにあるかどうかにかかわらず、10分ごとに緯度と経度を取得します。

私はservices、Thread、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

緯度と経度を取得します。

4

5 に答える 5

1

あなたの場所が更新されるたびにあなたの場所は実際にはデータベースに保存されません(via onLocationChanged(Location location))

あなたがすべきことはあなたのメソッドtimerにあなたの初期化をもたらすことです。OnCreate()次に、これらの変数を宣言します。

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

グローバルとして、メソッドで更新しonLocationChanged(Location location)ます。このように、タイマーがデータベース内の永続性を要求するときはいつでも、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);
}
于 2013-03-23T08:47:48.943 に答える
0

この方法を試してください、

この行の代わりに

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

私の論理を試してみてください、

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

また、 AlarmManagerの非常に良い例を見ることができます。

于 2013-03-23T04:56:47.853 に答える
0

開始コマンドでのみ位置を取得しようとしているのに、サービス終了コマンドが表示されません。

一般的に言えば-それは非常に複雑な問題です:10分の期間はAlarmManagerの使用を示唆します-それは大丈夫ですが...位置を取得することは時々10分よりはるかに長く続きます。GPS受信機は、位置を修正しようとすると異常な量のバッテリーを消費するため、状況によっては、GPSのオン/オフを定期的に切り替えると、オンのままにするよりも多くのバッテリーが消費される可能性があります。いくつかの「緩い圧縮」を検討してください-本当に必要な場合(つまり、時間、粗い位置の変更など)にのみGPSを呼び出すために異なる位置プロバイダーを組み合わせます

于 2013-03-23T09:59:51.437 に答える
0

私はこの方法を使用して、問題を解決しています。

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

これが正しいか間違っているかはわかりませんが、私のために働いてください。ガイドラインを提供してくれた@Lucifer、@ Maya mAku、@piotrpoに感謝します。

于 2013-03-25T05:08:26.327 に答える
0
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);
                     }
于 2014-02-26T07:39:08.303 に答える