我正在Android Studio中制作一个应用程序,用户可以在其中将当前的经纬度保存在Firebase中。我正在使用此代码:
public class SaveLocationActivity extends AppCompatActivity implements LocationListener {
TextView saveLatitude, saveLongitude;
Button saveLocationBtn;
FirebaseDatabase firebaseDatabase;
DatabaseReference databaseReference;
LocationManager locationManager;
Double latitude,longitude;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_save_location);
firebaseDatabase = FirebaseDatabase.getInstance();
databaseReference = firebaseDatabase.getReference().child("User");
saveLatitude = findViewById(R.id.saveLatitude);
saveLongitude = findViewById(R.id.saveLongitude);
saveLocationBtn = findViewById(R.id.saveLocationBtn);
if (ContextCompat.checkSelfPermission(getApplicationContext(), android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getApplicationContext(), android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION, android.Manifest.permission.ACCESS_COARSE_LOCATION}, 101);
}
saveLocationBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
getLocation();
}
});
}
public void getLocation() {
try {
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000, 5, SaveLocationActivity.this);
}
catch (SecurityException e)
{
e.printStackTrace();
}
}
@Override
public void onLocationChanged(Location location)
{
latitude=location.getLatitude();
String latStr=latitude.toString();
longitude=location.getLongitude();
String longStr=longitude.toString();
saveLatitude.setText(latStr);
saveLongitude.setText(longStr);
databaseReference.push().setValue("Latitude : "+latStr);
databaseReference.push().setValue("Longitude : "+longStr);
Toast.makeText(SaveLocationActivity.this, "Location Saved !!!", Toast.LENGTH_LONG).show();
Intent i=new Intent(SaveLocationActivity.this,DisplayProfile.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(i);
SaveLocationActivity.this.finish();
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
Toast.makeText(SaveLocationActivity.this, "Please Enable GPS and Internet !!!", Toast.LENGTH_SHORT).show();
}
}
现在,每当我在手机上运行此应用程序时,它都会显示Toast消息“请启用GPS和Internet !!!”尽管我的手机上有“我的位置”,也有正常的互联网连接。我实际上是使用我的家庭wifi进行互联网连接。如果有人在我的代码中发现任何错误,请告知我,也请提出可能的解决方案。
答案 0 :(得分:0)
您是否已将此权限添加到清单中?
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>