2

我正在开发一个 gps 程序,我每 5 分钟获取一次 gps 值,它工作得很好,但我必须存储我得到的值。它每 5 分钟刷新一次,我只有一个文本视图,因此在刷新新值时它会删除旧值。

这是我的代码。

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
         Intent intent = new Intent("android.location.GPS_ENABLED_CHANGE");
         intent.putExtra("enabled", true);
         this.sendBroadcast(intent);

        String provider = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
        if(!provider.contains("gps")){ //if gps is disabled
            final Intent poke = new Intent();
            poke.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider"); 
            poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
            poke.setData(Uri.parse("3")); 
            this.sendBroadcast(poke);


        }
    {
        //initialize location manager
        manager =  (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        //check if GPS is enabled
        //if not, notify user with a toast
        if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER)); else {
            //get a location provider from location manager
            //empty criteria searches through all providers and returns the best one
            String providerName = manager.getBestProvider(new Criteria(), true);
            Location location = manager.getLastKnownLocation(providerName);

            TextView tv = (TextView)findViewById(R.id.locationResults);
            if (location != null) {
                tv.setText(location.getLatitude() + " latitude, " + location.getLongitude() + " longitude");
            } else {
                tv.setText("Last known location not found. Waiting for updated location...");
            }
            //sign up to be notified of location updates every 15 seconds - for production code this should be at least a minute
            manager.requestLocationUpdates(providerName, 60000, 1, this);
        }
    }
}

    @Override
    public void onLocationChanged(Location location) {
        TextView tv = (TextView)findViewById(R.id.locationResults);
        if (location != null) {
            tv.setText(location.getLatitude() + " latitude, " + location.getLongitude() + " longitude");
        } else {
            tv.setText("Problem getting location");
        }
    }

    @Override
    public void onProviderDisabled(String arg0) {}

    @Override
    public void onProviderEnabled(String arg0) {}

    @Override
    public void onStatusChanged(String arg0, int arg1, Bundle arg2) {}

    // Find the closest Bart Station
    public String findClosestBart(Location loc) {
        double lat = loc.getLatitude();
        double lon = loc.getLongitude();

        double curStatLat = 0;
        double curStatLon = 0;
        double shortestDistSoFar = Double.POSITIVE_INFINITY;
        double curDist;
        String curStat = null;
        String closestStat = null;

        //sort through all the stations
        // write some sort of for loop using the API.

        curDist = Math.sqrt( ((lat - curStatLat) * (lat - curStatLat)) +
                        ((lon - curStatLon) * (lon - curStatLon)) );
        if (curDist < shortestDistSoFar) {
            closestStat = curStat;
        }

        return closestStat;

        }   

谢谢你。

4

3 回答 3

1

您可以将 Textview 的值存储到文件中以进行持久性存储。正确研究我的答案,我正在您现有的代码中添加一个文件存储方法,

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
         Intent intent = new Intent("android.location.GPS_ENABLED_CHANGE");
         intent.putExtra("enabled", true);
         this.sendBroadcast(intent);

        String provider = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
        if(!provider.contains("gps")){ //if gps is disabled
            final Intent poke = new Intent();
            poke.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider"); 
            poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
            poke.setData(Uri.parse("3")); 
            this.sendBroadcast(poke);


        }
    {
        //initialize location manager
        manager =  (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        //check if GPS is enabled
        //if not, notify user with a toast
        if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER)); else {
            //get a location provider from location manager
            //empty criteria searches through all providers and returns the best one
            String providerName = manager.getBestProvider(new Criteria(), true);
            Location location = manager.getLastKnownLocation(providerName);

            TextView tv = (TextView)findViewById(R.id.locationResults);
            if (location != null) {
                tv.setText(location.getLatitude() + " latitude, " + location.getLongitude() + " longitude");
            } else {
                tv.setText("Last known location not found. Waiting for updated location...");
            }
            //sign up to be notified of location updates every 15 seconds - for production code this should be at least a minute
            manager.requestLocationUpdates(providerName, 60000, 1, this);
        }
    }
}

    @Override
    public void onLocationChanged(Location location) {
        TextView tv = (TextView)findViewById(R.id.locationResults);
        if (location != null) {
            tv.setText(location.getLatitude() + " latitude, " + location.getLongitude() + " longitude");
          // I have added this line
          appendData ( location.getLatitude() + " latitude, " + location.getLongitude() + " longitude" );
        } else {
            tv.setText("Problem getting location");
        }
    }

    @Override
    public void onProviderDisabled(String arg0) {}

    @Override
    public void onProviderEnabled(String arg0) {}

    @Override
    public void onStatusChanged(String arg0, int arg1, Bundle arg2) {}

    // Find the closest Bart Station
    public String findClosestBart(Location loc) {
        double lat = loc.getLatitude();
        double lon = loc.getLongitude();

        double curStatLat = 0;
        double curStatLon = 0;
        double shortestDistSoFar = Double.POSITIVE_INFINITY;
        double curDist;
        String curStat = null;
        String closestStat = null;

        //sort through all the stations
        // write some sort of for loop using the API.

        curDist = Math.sqrt( ((lat - curStatLat) * (lat - curStatLat)) +
                        ((lon - curStatLon) * (lon - curStatLon)) );
        if (curDist < shortestDistSoFar) {
            closestStat = curStat;
        }

        return closestStat;

        }   
     // method to write in file 
public void appendData(String text)
{       
   File dataFile = new File("sdcard/gpsData.txt");
   if (!dataFile.exists())
   {
      try
      {
         dataFile.createNewFile();
      } 
      catch (IOException e)
      {
         // TODO Auto-generated catch block
         e.printStackTrace();
      }
   }
   try
   {
      //BufferedWriter for performance, true to set append to file flag
      BufferedWriter buf = new BufferedWriter(new FileWriter(dataFile, true)); 
      buf.append(text);
      buf.newLine();
      buf.close();
   }
   catch (IOException e)
   {
      // TODO Auto-generated catch block
      e.printStackTrace();
   }
}

您需要在 AndroidManifest.xml 中写入以下权限

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
于 2013-04-20T05:18:05.353 回答
0

好吧,您有很多持久性选项,但在这种情况下,最好使用SharedPreferences

于 2013-04-20T05:04:48.877 回答
0

在不确切知道您需要对保存的数据做什么的情况下,没有人可以肯定地说。如果您需要临时存储,ArrayList是一个不错的选择。您可以创建一个新的 ArrayList,然后在使用它的同时将值放入其中setText()。如果您想要永久的东西,那么您可能希望将其存储在数据库或文件中。查看存储选项

此外,在这种情况下,一个好主意可能是将其ArrayList临时存储,然后使用该列表将它们传输到文件或数据库以进行永久存储(如果这是您想要的)

另一种临时存储它并可能稍后保存在某个地方的方法是HashMap。也许某种形式的东西HashMap<String, HashMap<String, String>>。由于我们不知道您对数据的确切意图,因此示例可能无穷无尽,但也许这会给您一个很好的起点,因此您可以决定什么最适合您,然后您可以在 SO 和 Google 上找到许多示例你的选择

于 2013-04-20T05:09:20.687 回答