#java #android #android-intent #geolocation
Вопрос:
Я пытаюсь передать текущее местоположение пользователя из одного действия в другое, но это местоположение не отображается в другом действии. Кнопка определения местоположения работает-она принимает текущее местоположение пользователя, — но при попытке передать текущее местоположение с помощью Намерения другому действию она там не отображается. Я реализовал API автозаполнения Google(для любого местоположения, указанного пользователем) в том же действии (LocationActivity), что и текущее местоположение. Я новичок в Android, поэтому, пожалуйста, направьте меня, любая помощь будет признательна 🙂
public class LocationActivity extends AppCompatActivity {
TextView txtViewLocation;
//editText for LocationActivity
private EditText editTextLoc;
Button btLocation;
//initialize variable
TextView tvLatitude,tvLongitude,tvLocation;
FusedLocationProviderClient fusedLocationProviderClient ;
LocationRequest mLocationRequest;
//Declare a Variable FLAG in A1 as
public static int FLAG;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_location);
txtViewLocation= findViewById(R.id.txtViewToolbar);
//editText for google autocomplete api
editTextLoc = findViewById(R.id.editTxtLoc);
btLocation = findViewById(R.id.bt_location);
tvLatitude = findViewById(R.id.tv_latitude);
tvLongitude = findViewById(R.id.tv_longitude);
tvLocation = findViewById(R.id.tv_address);
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient
(LocationActivity.this);
//initialize fckin Places
Places.initialize(getApplicationContext(), "AIzaSyDqe72VPsqzlTNugI5xfc26Yv6sGvLUtf8");
//Set editText non focusabable
editTextLoc.setFocusable(false);
editTextLoc.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//initialize place filed list
List<Place.Field> fields = Arrays.asList(Place.Field.ADDRESS,
Place.Field.LAT_LNG, Place.Field.NAME);
// Start the autocomplete intent.
Intent intentAutocomplete = new Autocomplete.IntentBuilder(AutocompleteActivityMode.FULLSCREEN,
fields)
.build(LocationActivity.this);
startActivityForResult(intentAutocomplete, 150);
}
});
btLocation.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//check location
if(ActivityCompat.checkSelfPermission(LocationActivity.this, Manifest.permission
.ACCESS_FINE_LOCATION)== PackageManager.PERMISSION_GRANTED amp;amp;
ActivityCompat.checkSelfPermission(LocationActivity.this, Manifest.permission
.ACCESS_COARSE_LOCATION)== PackageManager.PERMISSION_GRANTED
) {
getCurrentLocation();
}else {
//when permission is not granted
//request permission
ActivityCompat.requestPermissions(LocationActivity.this,new String[]
{Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION},1);
}
}
});
}//bracket over for onCreate
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case 150:
if (resultCode == RESULT_OK) {
//When success
// initialize place
Place place = Autocomplete.getPlaceFromIntent(data);
String placeString =place.getAddress();
//Then navigate to MainActivity(homepage) with address or data
Intent intentBackToMain = new Intent(getApplicationContext(), MainActivity.class);
intentBackToMain.putExtra("place",placeString);
startActivity(intentBackToMain);
} else if (resultCode == AutocompleteActivity.RESULT_ERROR) {
//When error
//initialize status
Status status = Autocomplete.getStatusFromIntent(data);
//Display toast
Toast.makeText(getApplicationContext(), status.getStatusMessage(),
Toast.LENGTH_SHORT).show();
}
break;
default:
}
}
@Override
public void onRequestPermissionsResult(int requestCode2, @NonNull String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode2, permissions, grantResults);
switch (requestCode2) {
case 1:
if (grantResults.length > 0 amp;amp; (grantResults[0] grantResults[1] ==
PackageManager.PERMISSION_GRANTED)) {
//WHEN permission granted
//call method
getCurrentLocation();
} else {
//when permission denied
Toast.makeText(getApplicationContext(),"permission denied",Toast.LENGTH_SHORT).show();
}
break;
default:
}
}
@SuppressLint("MissingPermission")
private void getCurrentLocation() {
//initialize location manager
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
//CHECK CONDITION
if(locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)
||
locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)){
//when location srvice is enabled
//get last location
fusedLocationProviderClient.getLastLocation().addOnCompleteListener(new OnCompleteListener<Location>() {
@Override
public void onComplete(@NonNull Task<Location> task) {
//initialize location
Location location =task.getResult();
//check condition
if(location != null){
Geocoder geocoder = new Geocoder(LocationActivity.this, Locale.getDefault());
//when location result is not null
try {
List<Address>addresses = geocoder.getFromLocation(location.getLatitude(),
location.getLongitude(),1);
tvLocation.setText(addresses.get(0).getAddressLine(0));
String currentAddressString = tvLocation.getText().toString();
//Then navigate to MainActivity(homepage) with address or data
Intent currLocToMain = new Intent(LocationActivity.this, MainActivity.class);
currLocToMain.putExtra("currentLocString", currentAddressString);
startActivity(currLocToMain);
} catch (IOException e) {
e.printStackTrace();
}
}else{
//when location result is null
//initialize loction request
mLocationRequest = LocationRequest.create();
mLocationRequest.setInterval(100000);
mLocationRequest.setFastestInterval(1000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setNumUpdates(1);
//initialize location callBack
LocationCallback locationCallback = new LocationCallback() {
@Override
public void onLocationResult(@NonNull LocationResult locationResult) {
Geocoder geocoder = new Geocoder(LocationActivity.this, Locale.getDefault());
//initialize location
Location location1 =locationResult.getLastLocation();
List<Address>addresses = null;
try {
addresses = geocoder.getFromLocation(location.getLatitude(),
location.getLongitude(),1);
String currentAddressString = addresses.get(0).getAddressLine(0);
//Then navigate to MainActivity(homepage) with address or data
Intent currLocToMain = new Intent(getApplicationContext(), MainActivity.class);
currLocToMain.putExtra("current",currentAddressString);
startActivity(currLocToMain);
} catch (IOException e) {
e.printStackTrace();
}
}
};
//request location updates
fusedLocationProviderClient.requestLocationUpdates(mLocationRequest,
locationCallback, Looper.myLooper());
}
}
});
}else {
//when location service is not enabled
//open location setting
startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS)
.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
}
}
}
MainActivity
public class MainActivity extends AppCompatActivity {
private Toolbar toolbar;
private FirebaseAuth auth;
private Button logoutButton;
private TextView txtViewLocation;
private String data;
private String currentLocString;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar=findViewById(R.id.myAppBar);
txtViewLocation= findViewById(R.id.txtViewToolbar);
currentLocString=getIntent().getStringExtra("currentLocString");
txtViewLocation.setText(currentLocString);
data = getIntent().getStringExtra("place");
txtViewLocation.setText(data);
setSupportActionBar(toolbar);
auth = FirebaseAuth.getInstance();
logoutButton = findViewById(R.id.btnLogOut);
txtViewLocation.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intentLoc = new Intent(getApplicationContext(),LocationActivity.class);
startActivity(intentLoc);
// Activity is started with requestCode 2
}
});
logoutButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
auth.signOut();
startActivity(new Intent(MainActivity.this,SendOTPActivity.class));
finish();
}
});
}//onCreate over here
@Override
protected void onStart() {
super.onStart();
FirebaseUser currentUser = auth.getCurrentUser();
if(currentUser == null){
startActivity(new Intent(MainActivity.this,SendOTPActivity.class));
finish();
}
}
}