我正在尝试通过 GPS 获取当前位置。但我的应用程序意外关闭。我无法得到原因。我在 AndroidManifest.xml 中添加了权限:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
我正在尝试的代码如下:
公共类 MainActivity 扩展 Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
public void getLoc()
{
LocationManager manager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
LocationListener listener = new MyLocationListener();
manager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 5000, 10, listener);
}
public class MyLocationListener implements LocationListener {
@Override
public void onLocationChanged(Location loc)
{
loc.getLatitude();
loc.getLongitude();
String Text = "My current location is: " + "Latitude = " + loc.getLatitude() + "Longitude = " + loc.getLongitude();
Toast.makeText( getApplicationContext(), Text, Toast.LENGTH_SHORT).show();
}
@Override
public void onProviderDisabled(String provider)
{
Toast.makeText( getApplicationContext(), "Gps Disabled", Toast.LENGTH_SHORT ).show();
}
@Override
public void onProviderEnabled(String provider)
{
Toast.makeText( getApplicationContext(), "Gps Enabled", Toast.LENGTH_SHORT).show();
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras)
{ }
}
}