我試圖在每次位置更改時將經度和緯度值寫入文本文件。其結果應該是存儲在SD卡上的文本文件,其中包含經度和緯度值列表。應用程序成功獲取經度和緯度,並彈出Toast通知,說明文件已成功保存。但是,我無法在SD卡的根目錄中找到該文本文件。需要在根SD卡中找到.txt文件的位置
下面是代碼:
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)
{
}
}
}
所以基本上,這裏是位置值的文件?我覺得我錯過了一些很明顯的東西在這裏...
我不認爲/ SD卡/將是確定的。使用Environment.getExternalStorageDirectory()(並不總是SD!) –
不要忘記取得許可 –
Ankit
除了正確發現適當的路徑,在較新的設備,不要忘記你需要調用媒體掃描器才能使用諸如MTP連接到PC的文件。 –