This is the code i have to check for my current lcoation. I have Wifi turned on my android device but networkIsEnabled is always false.
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
boolean networkIsEnabled = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
Location loc = lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
double lat = loc.getLatitude();
double lng = loc.getLongitude();
I ran into a similar problem.
Your manifest should have:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<application ....
<receiver
android:name="com.your_package.ConnectionChangeReceiver"
android:label="NetworkConnection">
<intent-filter>
<action android:name="android.net.wifi.WIFI_STATE_CHANGED"/>
<action android:name="android.net.wifi.STATE_CHANGE"/>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
</receiver>
</application>
The block in the application tag isn't necessary if you just want your current location, but if you're looking to actively detect when the network state changes, then you'll need that. In that case, ConnectionChangeReceiver would be your class that extends BroadcastReceiver.
Hopefully this helps.
EDIT:
Just to clarify, network refers to 3/4G. If your WIFI is on with airplanemode on, network will be false. You have to check both WIFI AND 3/4G.
ConnectivityManager conMngr = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo wifi = conMngr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
NetworkInfo mobile = conMngr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
if(wifi.isAvailable() && wifi.isConnected())
// available + connected
if(mobile.isAvailable() && mobile.isConnected())
// available + connected
Note: in order to check the wifi state like this, you need "ACCESS_WIFI_STATE" in your manifest. I added it above.
EDIT 2:
This is how you get LAT/LONG:
GPSTracker Class: http://pastebin.com/ESXzfdcu
Class you want lag/long in:
GPSTracker gps = new GPSTracker(MainActivity.this);
if(gps.canGetLocation()) {
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show();
}else {
gps.showSettingsAlert();
}
Instead of displaying the lat/long in a toast, you can simply set some lag/long variables and use them where ever you need.