1. Are you ready for the Galaxy S20? Here is everything we know so far!

how to find location of user without gps?

Discussion in 'Android Development' started by ratemo, Jan 18, 2020.

  1. ratemo

    ratemo Lurker
    Thread Starter

    Here is the register code for a dating app, i need to find location without using gps since some phones have only gps in battery mode.

    Code (Text):
    1. package com.ratemo.universe.Start;
    2. import android.Manifest;
    3. import android.app.DatePickerDialog;
    4. import android.app.ProgressDialog;
    5. import android.content.Context;
    6. import android.content.DialogInterface;
    7. import android.content.Intent;
    8. import android.location.Address;
    9. import android.location.Geocoder;
    10. import android.location.Location;
    11. import android.location.LocationManager;
    12. import android.os.Build;
    13. import androidx.annotation.NonNull;
    14. import androidx.fragment.app.DialogFragment;
    15. import androidx.core.content.ContextCompat;
    16. import androidx.core.content.PermissionChecker;
    17. import androidx.appcompat.app.AlertDialog;
    18. import androidx.appcompat.app.AppCompatActivity;
    19. import android.os.Bundle;
    20. import android.text.TextUtils;
    21. import android.view.View;
    22. import android.view.WindowManager;
    23. import android.widget.Button;
    24. import android.widget.DatePicker;
    25. import android.widget.EditText;
    26. import android.widget.RadioButton;
    27. import android.widget.RadioGroup;
    28. import android.widget.TextView;
    29. import android.widget.Toast;
    30. import com.google.android.gms.common.ConnectionResult;
    31. import com.google.android.gms.common.GoogleApiAvailability;
    32. import com.google.android.gms.location.FusedLocationProviderClient;
    33. import com.google.android.gms.location.LocationRequest;
    34. import com.google.android.gms.tasks.OnCompleteListener;
    35. import com.google.android.gms.tasks.OnSuccessListener;
    36. import com.google.android.gms.tasks.Task;
    37. import com.google.firebase.Timestamp;
    38. import com.google.firebase.auth.AuthResult;
    39. import com.google.firebase.auth.FirebaseAuth;
    40. import com.google.firebase.auth.FirebaseUser;
    41. import com.google.firebase.firestore.FirebaseFirestore;
    42. import com.nabinbhandari.android.permissions.PermissionHandler;
    43. import com.nabinbhandari.android.permissions.Permissions;
    44. import com.ratemo.universe.Extra.DateClass;
    45. import com.ratemo.universe.Main.MainActivity;
    46. import com.ratemo.universe.R;
    47. import java.io.IOException;
    48. import java.text.SimpleDateFormat;
    49. import java.util.ArrayList;
    50. import java.util.Calendar;
    51. import java.util.HashMap;
    52. import java.util.List;
    53. import java.util.Locale;
    54. import java.util.Map;
    55. public class RegisterActivity extends AppCompatActivity implements DatePickerDialog.OnDateSetListener {
    56. String string_city;
    57. String string_state;
    58. String string_country;
    59. String string_location;
    60. String stringLatitude;
    61. String stringLongitude;
    62. String stringLooking;
    63. private FirebaseAuth firebaseAuth;
    64. private FirebaseUser firebaseUser;
    65. private FirebaseFirestore firebaseFirestore;
    66. private Button btnRegisterPageRegister;
    67. private Button btnRegisterPageLogin;
    68. private EditText editTextRegisterName;
    69. private EditText editTextRegisterEmail;
    70. private EditText editTextRegisterPassword;
    71. private RadioGroup radioGroupRegisterGender;
    72. private RadioButton radioButtonRegisterGender;
    73. private TextView textViewRegisterBirthday;
    74. private FusedLocationProviderClient fusedLocationProviderClient;
    75. private LocationRequest locationRequest;
    76. LocationManager locationManager;
    77. ProgressDialog dialog;
    78. [USER=1021285]@override[/USER]
    79. protected void onCreate(Bundle savedInstanceState) {
    80. super.onCreate(savedInstanceState);
    81. setContentView(R.layout.register_activity);
    82. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
    83. getWindow().setFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS,
    84. WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
    85. }
    86. firebaseAuth = FirebaseAuth.getInstance();
    87. firebaseFirestore = FirebaseFirestore.getInstance();
    88. btnRegisterPageRegister = (Button) findViewById(R.id.btnRegisterPageRegister);
    89. btnRegisterPageLogin = (Button) findViewById(R.id.btnRegisterPageLogin);
    90. editTextRegisterName = (EditText) findViewById(R.id.editTextRegisterName);
    91. editTextRegisterEmail = (EditText) findViewById(R.id.editTextRegisterEmail);
    92. editTextRegisterPassword = (EditText) findViewById(R.id.editTextRegisterPassword);
    93. textViewRegisterBirthday = (TextView) findViewById(R.id.textViewRegisterBirthday);
    94. radioGroupRegisterGender = findViewById(R.id.radioGroupRegisterGender);
    95. dialog = new ProgressDialog(RegisterActivity.this);
    96. dialog.setMessage("Loading...");
    97. dialog.setCancelable(false);
    98. locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    99. LocationPremissionCheck();
    100. GooglePlayServiceCheck();
    101. GPSLocationServiceCheck();
    102. btnRegisterPageLogin.setOnClickListener(new View.OnClickListener() {
    103. [USER=1021285]@override[/USER]
    104. public void onClick(View v) {
    105. Intent intent = new Intent(RegisterActivity.this, LoginActivity.class);
    106. intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    107. startActivity(intent);
    108. }
    109. });
    110. textViewRegisterBirthday.setOnClickListener(new View.OnClickListener() {
    111. [USER=1021285]@override[/USER]
    112. public void onClick(View v) {
    113. DialogFragment datePicker = new DateClass();
    114. datePicker.show(getSupportFragmentManager(), "Date Picker");
    115. }
    116. });
    117. btnRegisterPageRegister.setOnClickListener(new View.OnClickListener() {
    118. [USER=1021285]@override[/USER]
    119. public void onClick(View v) {
    120. string_city = string_state;
    121. string_state= string_city;
    122. string_country = string_location;
    123. if (radioButtonRegisterGender != null) {
    124. if (string_city != null && !string_city.equals("city") &&
    125. string_state != null && !string_state.equals("state") &&
    126. string_country != null && !string_country.equals("country")) {
    127. final String stringName = editTextRegisterName.getText().toString();
    128. final String stringEmail = editTextRegisterEmail.getText().toString();
    129. final String stringPassword = editTextRegisterPassword.getText().toString();
    130. final String stringGender = radioButtonRegisterGender.getText().toString();
    131. final String stringBirthday = textViewRegisterBirthday.getText().toString();
    132. if (stringGender.equals("Male")) {
    133. stringLooking = "Woman";
    134. } else {
    135. stringLooking = "Man";
    136. }
    137. if (!TextUtils.isEmpty(stringName) &&
    138. !TextUtils.isEmpty(stringEmail) &&
    139. !TextUtils.isEmpty(stringPassword) &&
    140. !TextUtils.isEmpty(stringGender) &&
    141. !TextUtils.isEmpty(stringBirthday)) {
    142. dialog.show();
    143. firebaseAuth.createUserWithEmailAndPassword(stringEmail, stringPassword).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
    144. [USER=1021285]@override[/USER]
    145. public void onComplete(@NonNull Task<AuthResult> task) {
    146. if (task.isSuccessful()) {
    147. firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
    148. String currentUser = firebaseUser.getUid();
    149. Map<String, Object> userProfile = new HashMap<>();
    150. userProfile.put("user_uid", currentUser);
    151. userProfile.put("user_email", stringEmail);
    152. userProfile.put("user_epass", stringPassword);
    153. userProfile.put("user_name", stringName);
    154. userProfile.put("user_gender", stringGender);
    155. userProfile.put("user_birthday", stringBirthday);
    156. userProfile.put("user_birthage", AgeUser(stringBirthday));
    157. userProfile.put("user_city", string_city);
    158. userProfile.put("user_state", string_state);
    159. userProfile.put("user_country", string_country);
    160. userProfile.put("user_location", string_location);
    161. userProfile.put("user_thumb", "thumb");
    162. userProfile.put("user_image", "image");
    163. userProfile.put("user_cover", "cover");
    164. userProfile.put("user_status", "offline");
    165. userProfile.put("user_looking", stringLooking);
    166. userProfile.put("user_about", "Hi! Everybody I am newbie here.");
    167. userProfile.put("user_latitude", stringLatitude);
    168. userProfile.put("user_longitude", stringLongitude);
    169. userProfile.put("user_online", Timestamp.now());
    170. userProfile.put("user_joined", Timestamp.now());
    171. firebaseFirestore.collection("users")
    172. .document(currentUser)
    173. .set(userProfile)
    174. .addOnCompleteListener(new OnCompleteListener<Void>() {
    175. [USER=1021285]@override[/USER]
    176. public void onComplete(@NonNull Task<Void> task) {
    177. if (task.isSuccessful()) {
    178. Intent intent = new Intent(RegisterActivity.this, MainActivity.class);
    179. startActivity(intent);
    180. finish();
    181. dialog.dismiss();
    182. } else {
    183. Toast.makeText(RegisterActivity.this, "Something went wrong! Please try again!", Toast.LENGTH_SHORT).show();
    184. dialog.dismiss();
    185. }
    186. }
    187. });
    188. } else {
    189. Toast.makeText(RegisterActivity.this, "Please check errors to proceed!", Toast.LENGTH_SHORT).show();
    190. }
    191. }
    192. });
    193. } else {
    194. Toast.makeText(RegisterActivity.this, "Please Fill in all the details to proceed!", Toast.LENGTH_SHORT).show();
    195. }
    196. } else {
    197. Toast.makeText(RegisterActivity.this, "Please turn on Location service to continue.", Toast.LENGTH_SHORT).show();
    198. }
    199. } else {
    200. Toast.makeText(RegisterActivity.this, "Please Fill in all the details to proceed!", Toast.LENGTH_SHORT).show();
    201. }
    202. }
    203. });
    204. }
    205. public void radioButtonRegisterGender(View view) {
    206. int radioId = radioGroupRegisterGender.getCheckedRadioButtonId();
    207. radioButtonRegisterGender = findViewById(radioId);
    208. }
    209. [USER=1021285]@override[/USER]
    210. public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
    211. Calendar calendar = Calendar.getInstance();
    212. calendar.set(Calendar.YEAR, year);
    213. calendar.set(Calendar.MONTH, month);
    214. calendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
    215. SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy");
    216. String strDate = format.format(calendar.getTime());
    217. if (year > 2000) {
    218. Toast.makeText(this,
    219. "Sorry! you dont meet our user registration minimum age limits policy now. Please register with us after some time. Thank you for trying our app now!",
    220. Toast.LENGTH_LONG).show();
    221. textViewRegisterBirthday.setText("");
    222. } else {
    223. textViewRegisterBirthday.setText(strDate);
    224. }
    225. }
    226. private String AgeUser(String stringDateUser) {
    227. String[] arrayDateUser = stringDateUser.split("-");
    228. int day = Integer.valueOf(arrayDateUser[0]);
    229. int month = Integer.valueOf(arrayDateUser[1]);
    230. int year = Integer.valueOf(arrayDateUser[2]);
    231. Calendar dob = Calendar.getInstance();
    232. Calendar today = Calendar.getInstance();
    233. dob.set(year, month, day);
    234. int age = today.get(Calendar.YEAR) - dob.get(Calendar.YEAR);
    235. if (today.get(Calendar.DAY_OF_YEAR) < dob.get(Calendar.DAY_OF_YEAR)) {
    236. age--;
    237. }
    238. Integer ageInt = new Integer(age);
    239. String ageS = ageInt.toString();
    240. return ageS;
    241. }
    242. private void LocationPremissionCheck() {
    243. String[] permissions = {Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION};
    244. String rationale = "Please provide location permission so that you can ...";
    245. Permissions.Options options = new Permissions.Options()
    246. .setRationaleDialogTitle("Location Permission")
    247. .setSettingsDialogTitle("Warning");
    248. Permissions.check(this/*context*/, permissions, null/*rationale*/, null/*options*/, new PermissionHandler() {
    249. [USER=1021285]@override[/USER]
    250. public void onGranted() {
    251. LocationRequest();
    252. }
    253. [USER=1021285]@override[/USER]
    254. public void onDenied(Context context, ArrayList<String> deniedPermissions) {
    255. super.onDenied(context, deniedPermissions);
    256. LocationPremissionCheck();
    257. }
    258. });
    259. }
    260. private void LocationRetreive(Double locationLatitude, Double locationLongitude) {
    261. try {
    262. Geocoder geocoder = new Geocoder(this, Locale.getDefault());
    263. List<Address> addresses = geocoder.getFromLocation(locationLatitude, locationLongitude, 1);
    264. if (addresses != null && addresses.size() > 0) {
    265. string_city = addresses.get(0).getLocality();
    266. string_state = addresses.get(0).getAdminArea();
    267. string_country = addresses.get(0).getCountryName();
    268. string_location = addresses.get(0).getAddressLine(0);
    269. if (string_country == null) {
    270. if (string_state != null) {
    271. string_country = string_state;
    272. } else if (string_city != null) {
    273. string_country = string_city;
    274. } else {
    275. string_country = "null";
    276. }
    277. }
    278. if (string_city == null) {
    279. if (string_state != null) {
    280. string_city = string_state;
    281. } else {
    282. string_city = string_country;
    283. }
    284. }
    285. if (string_state == null) {
    286. if (string_city != null) {
    287. string_state = string_city;
    288. } else {
    289. string_state = string_country;
    290. }
    291. }
    292. if (string_location == null) {
    293. string_location = "Null";
    294. }
    295. }
    296. } catch (IOException e) {
    297. e.printStackTrace();
    298. Toast.makeText(RegisterActivity.this, e.toString(), Toast.LENGTH_SHORT).show();
    299. }
    300. }
    301. private void LocationRequest() {
    302. if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) ==
    303. PermissionChecker.PERMISSION_GRANTED &&
    304. ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) ==
    305. PermissionChecker.PERMISSION_GRANTED) {
    306. fusedLocationProviderClient = new FusedLocationProviderClient(this);
    307. fusedLocationProviderClient.getLastLocation().addOnSuccessListener(new OnSuccessListener<Location>() {
    308. [USER=1021285]@override[/USER]
    309. public void onSuccess(Location location) {
    310. if (location != null) {
    311. Double locationLatitude = location.getLatitude();
    312. Double locationLongitude = location.getLongitude();
    313. stringLatitude = locationLatitude.toString();
    314. stringLongitude = locationLongitude.toString();
    315. if (!stringLatitude.equals("0.0") && !stringLongitude.equals("0.0")) {
    316. LocationRetreive(locationLatitude, locationLongitude);
    317. } else {
    318. Toast.makeText(RegisterActivity.this,
    319. "Please turn on any GPS or location service and restart to use the app.Disable Power Saving Mode or Download GPS Essentials.", Toast.LENGTH_SHORT).show();
    320. }
    321. } else {
    322. Toast.makeText(RegisterActivity.this,
    323. "Please turn on any GPS or location service and restart to use the app. Disable power saving or download GPS Essentials", Toast.LENGTH_SHORT).show();
    324. }
    325. }
    326. });
    327. } else {
    328. LocationPremissionCheck();
    329. }
    330. }
    331. public boolean GooglePlayServiceCheck() {
    332. GoogleApiAvailability googleApiAvailability = GoogleApiAvailability.getInstance();
    333. int status = googleApiAvailability.isGooglePlayServicesAvailable(this);
    334. if (status != ConnectionResult.SUCCESS) {
    335. if (googleApiAvailability.isUserResolvableError(status)) {
    336. googleApiAvailability.getErrorDialog(this, status, 2404).show();
    337. }
    338. return false;
    339. }
    340. return true;
    341. }
    342. private void GPSLocationServiceCheck() {
    343. if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
    344. final AlertDialog.Builder builder = new AlertDialog.Builder(this);
    345. builder.setMessage("Your GPS seems to be disabled, enable it to use this app?")
    346. .setCancelable(false)
    347. .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
    348. public void onClick(@SuppressWarnings("unused") final DialogInterface dialog, @SuppressWarnings("unused") final int id) {
    349. startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
    350. }
    351. })
    352. .setNegativeButton("No", new DialogInterface.OnClickListener() {
    353. public void onClick(final DialogInterface dialog, @SuppressWarnings("unused") final int id) {
    354. dialog.cancel();
    355. Intent intent = new Intent(RegisterActivity.this, StartActivity.class);
    356. intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    357. startActivity(intent);
    358. finish();
    359. }
    360. });
    361. final AlertDialog alert = builder.create();
    362. alert.show();
    363. }
    364. }
    365. [USER=1021285]@override[/USER]
    366. protected void onStart() {
    367. super.onStart();
    368. GPSLocationServiceCheck();
    369. }
    370. }
     

    Advertisement

    #1 ratemo, Jan 18, 2020
    Last edited by a moderator: Jan 18, 2020
    racibennett likes this.
  2. Unforgiven

    Unforgiven ...eschew obfuscation...
    Moderator

    I moved this to the dev area for better exposure. I added code tags (example below) to make the syntax easier to read. Good luck!! :)

    Code Tags Usage:
    [code]Line 1
    Line 2
    Line 3
    [/code]

    Result:
    Code (Text):
    1. Line 1
    2. Line 2
    3. Line 3
    4.  
     
    ocnbrze likes this.
  3. ratemo

    ratemo Lurker
    Thread Starter

    Please can you sold this issue, I need to get location just like that of Instagram or Tinder without having to use gps
     
  4. Unforgiven

    Unforgiven ...eschew obfuscation...
    Moderator

    I'm not a developer, so I don't know the specifics. But can't you make requests to the OS via APIs for rough location (tower triangulation, wifi location) as opposed to fine (GPS)? Just a guess.
     
    ocnbrze likes this.
  5. Hadron

    Hadron Smoke me a kipper...
    VIP Member

    When you say "without gps" do you mean specifically without GPS or without using location services? Because "coarse location" just requires the network-based location access, and so will generally work even when GPS is disabled for any reason (though not for people like me who specify device-only location, which means GPS or nothing). If you need high precision then without GPS you are stuck: network-based location can be quite accurate in some environments, but spectacularly imprecise in others.

    If location services are disabled, or if the user denies location access to your app (as I do with Instagram - I've never installed Tinder) then of course you are out of luck. If I knew a way to do that I'd report it to Google as a bug to fix urgently, then to the press if they didn't act, since that would be a major privacy failure in the operating system.

    BTW I'm also not an android developer, so can't provide specific coding solutions.
     
    ocnbrze and Unforgiven like this.
Loading...

Share This Page

Loading...