每当位置更改时,我都尝试将经度和纬度值写入文本文件。结果应为存储在SD卡上的文本文件,其中包含经度和纬度值列表。该应用程序成功获取经度和纬度,并且弹出提示消息,提示文件已成功保存。但是,我在SD卡的根目录中找不到该文本文件。

这是代码:

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;

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

public class MainActivity extends Activity
{
TextView textlat;
TextView textlong;

@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    textlat = (TextView)findViewById(R.id.textlat);
    textlong = (TextView)findViewById(R.id.textlong);

    LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
    LocationListener ll = new mylocationlistener();
    lm.requestLocationUpdates(LocationManager.GPS_PROVIDER,
            10000, 0, ll);
}

private class mylocationlistener implements LocationListener
{

    @Override
    public void onLocationChanged(Location location)
    {
        if (location != null)
        {
            double pLong = location.getLongitude();
            double pLat = location.getLatitude();

            textlat.setText(Double.toString(pLat));
            textlong.setText(Double.toString(pLong));

            try
            {
                File myFile = new File("/sdcard/mysdfile.txt");
                myFile.createNewFile();
                FileOutputStream fOut = new FileOutputStream(myFile);
                OutputStreamWriter myOutWriter =
                                        new OutputStreamWriter(fOut);
                myOutWriter.append(textlat.getText());

                myOutWriter.close();
                fOut.close();
                Toast.makeText(getBaseContext(),
                        "Done writing SD 'mysdfile.txt'",
                        Toast.LENGTH_SHORT).show();
            }
            catch (Exception e)
            {
                Toast.makeText(getBaseContext(), e.getMessage(),
                        Toast.LENGTH_SHORT).show();
            }
        }
    }

    @Override
    public void onProviderDisabled(String provider)
    {

    }

    @Override
    public void onProviderEnabled(String provider)
    {


    }

    @Override
    public void onStatusChanged(String provider, int status,
            Bundle extras)
    {

    }
}
}


因此,基本上,具有位置值的文件在哪里?我觉得我这里确实缺少一些明显的东西...

最佳答案

您不应该尝试写入sdcard的根文件夹。由于安全问题,这将失败。尝试以下方法:

File dir = Environment.getExternalStoragePublicDirectory();
File myFile = new File(dir, "mysdfile.txt");


然后,您可以稍后在目录dir中找到该文件。如果您希望文件对应用程序是私有的,请使用Context.getExternalFilesDir()而不是Environment.getExternalStoragePublicDirectory()

另请参阅Storage Options上的指南主题

10-07 19:47
查看更多