【发布时间】:2019-04-07 06:03:03
【问题描述】:
我需要将我的位置存储到 Firebase 实时数据库中。以下代码仅在 Android 应用程序中有效并显示位置。我如何将此位置发送到 firebase?
public class MainActivity extends AppCompatActivity {
Button button;
TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.button);
textView = (TextView) findViewById(R.id.textView);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) { //check for sdk version
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M ) {
if (checkSelfPermission(android.Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED && checkSelfPermission(android.Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{android.Manifest.permission.ACCESS_COARSE_LOCATION}, 1000);
}else{
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Location location = locationManager .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
try{
String city = hereLocation(location.getLatitude(), location.getLongitude());
textView.setText(city);
}catch (Exception e)
{ e.printStackTrace();
Toast.makeText(MainActivity.this,"Not found!",Toast.LENGTH_LONG).show();
}
}
}
}
});
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
switch (requestCode){ //set the text value
case 1000:{
if(grantResults[0] == PackageManager.PERMISSION_GRANTED)
{
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
String city = hereLocation(location.getLatitude(),location.getLongitude());
textView.setText(city);
}else{
Toast.makeText(this,"permission is granted!",Toast.LENGTH_LONG).show();
}
break;
}
}
}
private String hereLocation(double lat, double lon){ //access geo location
String cityName = "";
Geocoder geocoder= new Geocoder(this ,Locale.getDefault());
List<Address> addresses;
try{
addresses = geocoder.getFromLocation(lat,lon, 10);
if(addresses.size()> 0){
for(Address adr:addresses) {
if (adr.getLocality() != null && adr.getLocality() .length()> 0) {
cityName = adr.getLocality();
break;
}
}
}
}catch (IOException e){
e.printStackTrace();
}
return cityName;
}
}
城市名称正在使用文本视图存储。它将给出设备所在的当前城市。我需要将此位置发送到 firebase 实时数据库。
【问题讨论】:
-
您的代码尚未显示与 Firebase 的交互。我建议开始使用Firebase documentation 或codelab。如果您在某个具体步骤上遇到困难,请分享minimal code that reproduces where you got stuck。
标签: java android firebase firebase-realtime-database