0

here is my code to get the location of user Please help me I'm stuck in this part

public class MainActivity extends AppCompatActivity {
LocationManager locationManager;
String provider;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    provider = locationManager.getBestProvider(new Criteria(), true);


    Location location =locationManager.getLastKnownLocation(provider);
    if (location!=null){
        Log.i("Location","Found");
    }
    else{
        Log.i("Location","Not Found");
    }


}

}

note:the location is enabled in my phone ,I'm connected to wifi ,I added 2 user permission for location,gps enabled

  • 2
    This will almost always return null. The only time it won't is if some other app is already using locations. If you actually need a location, call requestLocationUpdates or requestSingleLocation and wait for the callback. – Gabe Sechan Jun 19 '17 at 21:19
  • 1
    [Here is a sample app](https://github.com/commonsguy/cw-omnibus/tree/master/Location/Classic) demonstrating the techniques that Mr. Sechan mentioned in the preceding comment. Note that the proper use of `LocationManager` is covered in many books and courses on Android app development. – CommonsWare Jun 19 '17 at 21:20

0 Answers0