自动更新位置,无需重新启动应用程序

问题描述 投票:0回答:2

我正在构建一个简单的 Android 应用程序,它需要我自动更新位置。自动更新位置不仅会在恢复应用程序时更新,而且必须在应用程序打开时自动更新。该应用程序看起来与安装在车内的 GPS 系统相同。它获取准确的位置并始终更新当前位置。我想在这里做同样的事情。我正在 android 2.2 上构建这个应用程序。

这是我的代码:

 package com.example.map;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.content.Context;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.widget.TextView;
import android.widget.Toast;

public class MapActivity extends Activity implements LocationListener{
    private TextView latituteField, longitudeField, accuracyField, altitudeField, bearingField; 
    private LocationManager locationManager;
    private String provider;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_map);

    latituteField = (TextView) findViewById(R.id.TextView02);
    longitudeField = (TextView) findViewById(R.id.TextView04);
    accuracyField = (TextView) findViewById(R.id.textView1);
    altitudeField = (TextView) findViewById(R.id.textView2);
    bearingField = (TextView) findViewById(R.id.textView4);

    // Get the location manager
    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    // Define the criteria how to select the locatioin provider -> use default  
    Criteria criteria = new Criteria();
    provider = locationManager.getBestProvider(criteria, false);
    Location location = locationManager.getLastKnownLocation(provider);


    // Initialize the location fields
    if (location != null) {
      System.out.println("Provider " + provider + " has been selected.");
      onLocationChanged(location);
    } else {
      latituteField.setText("Location not available");
      longitudeField.setText("Location not available");
    }
  }

  /* Request updates at startup */
  @Override
  protected void onResume() {
    super.onResume();
    locationManager.requestLocationUpdates(provider, 400, 1, this);
  }

  /* Remove the locationlistener updates when Activity is paused */
  @Override
  protected void onPause() {
    super.onPause();
    locationManager.removeUpdates(this);
  }

  @Override
  public void onLocationChanged(Location location) {
    int lat = (int) (location.getLatitude());
    int lng = (int) (location.getLongitude());
    int acc = (int) (location.getAccuracy());
    int alt = (int) (location.getAltitude());
    int bearing = (int) (location.getBearing());
    latituteField.setText(String.valueOf(lat));
    longitudeField.setText(String.valueOf(lng));
    accuracyField.setText(String.valueOf(acc));
    altitudeField.setText(String.valueOf(alt));
    bearingField.setText(String.valueOf(bearing));

  }

  @Override
  public void onStatusChanged(String provider, int status, Bundle extras) {
    // TODO Auto-generated method stub

  }

  @Override
  public void onProviderEnabled(String provider) {
    Toast.makeText(this, "Enabled new provider " + provider,
        Toast.LENGTH_SHORT).show();

  }

  @Override
  public void onProviderDisabled(String provider) {
    Toast.makeText(this, "Disabled provider " + provider,
        Toast.LENGTH_SHORT).show();
  }

此代码仅在我恢复应用程序时更新位置值(我退出应用程序然后返回应用程序)。位置将在视图文本中更新。

我也尝试过这样做。像这样。

if(location != null){
    do{
        System.out.println("Provider " + provider + " has been selected.");
        onLocationChanged(location);
        locationManager.requestLocationUpdates(provider, 0, 0, this);
    }while(location != null);
    }
    else{
        latituteField.setText("Location not available");
        longitudeField.setText("Location not available");
    }

我将其添加到清单中。

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission>
<uses-permission android:name="android.permission.INTERNET" /> 

但是,此代码会使应用程序在真实手机中崩溃。有办法完成这个吗?

*注意:我在我的真实手机中测试了所有这些应用程序并尝试获取当前位置。每当文本视图获取位置的新值时,它就会发生变化,而无需暂停或退出应用程序。

android gps location
2个回答
1
投票

您必须将位置代码放入 ScheduledExecutor 服务中:

http://developer.android.com/reference/java/util/concurrent/ScheduledExecutorService.html

该函数在后台重复实现功能,例如每 30 秒或您指定的任何时间。

示例:

    scheduleTaskExecutor= Executors.newScheduledThreadPool(5);

    // This schedule a task to run every 10 seconds:

    scheduleTaskExecutor.scheduleAtFixedRate(new Runnable() {
      public void run() {


            try {                 


                //add your code you would like to be executed every 10 seconds.



            } catch (IOException e) {                          
               e.printStackTrace();                           
            }                                     


      }
    }, 0, 10, TimeUnit.SECONDS);

您可能还需要添加粗略位置的权限。


0
投票

如何在从一个区域跳转到另一个区域时自动更改Android手机中的位置指示后台显示?

© www.soinside.com 2019 - 2024. All rights reserved.