Monday, April 25, 2016

Get GPS current location coordinates and city name

 Get Current Location coordinates/GPS coordinates and get City name


I have already tested this app on my android phone and one more thing when you move line 10-20 meter you will get the new coordinates.

What is app does?

  • check gps is enable or disable
  • Get gps coordinates
  • Get the current city name.


 -------------------------------------------
App Name: GetMyCurrentLocation
Package Name: com.example.hemant.may_i_help_u

Android SDK: Android SDK 2.3.3 / API 10
Default Activity Name: MainActivity 

-------------------------------------------

package com.example.hemant.may_i_help_u;


import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;

import java.io.IOException;
import java.util.List;
import java.util.Locale;

public class MainActivity extends Activity implements OnClickListener {

private LocationManager locationMangaer=null;

private LocationListener locationListener=null;

private Button btnGetLocation = null;
private EditText editLocation = null;
private ProgressBar pb =null;

private static final String TAG = "Debug";
private Boolean flag = false;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);


//if you want to lock screen for always Portrait mode
setRequestedOrientation(ActivityInfo
.SCREEN_ORIENTATION_PORTRAIT);

pb = (ProgressBar) findViewById(R.id.progressBar1);
pb.setVisibility(View.INVISIBLE);

editLocation = (EditText) findViewById(R.id.editTextLocation);

btnGetLocation = (Button) findViewById(R.id.btnLocation);
btnGetLocation.setOnClickListener(this);

locationMangaer = (LocationManager)
getSystemService(Context.LOCATION_SERVICE);

}

@Override
public void onClick(View v) {
flag = displayGpsStatus();
if (flag) {

Log.v(TAG, "onClick");

editLocation.setText("Please!! move your device to"+
" see the changes in coordinates."+"\nWait..");

pb.setVisibility(View.VISIBLE);
locationListener = new MyLocationListener();

if ( Build.VERSION.SDK_INT >= 23 &&
ContextCompat.checkSelfPermission( MainActivity.this, android.Manifest.permission.ACCESS_FINE_LOCATION ) != PackageManager.PERMISSION_GRANTED &&
ContextCompat.checkSelfPermission( MainActivity.this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return ;
}
locationMangaer.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 10, locationListener);


} else {
alertbox("Gps Status!!", "Your GPS is: OFF");
}

}

/*----Method to Check GPS is enable or disable ----- */
private Boolean displayGpsStatus() {

LocationManager lm = (LocationManager)MainActivity.this.getSystemService(Context.LOCATION_SERVICE);
boolean gps_enabled = false;

try {
gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);

} catch(Exception ex) {}
return gps_enabled;
}

/*----------Method to create an AlertBox ------------- */
protected void alertbox(String title, String mymessage) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Your Device's GPS is Disable")
.setCancelable(false)
.setTitle("** Gps Status **")
.setPositiveButton("Gps On",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// finish the current activity
// AlertBoxAdvance.this.finish();
Intent myIntent = new Intent(
Settings.ACTION_SECURITY_SETTINGS);
startActivity(myIntent);
dialog.cancel();
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// cancel the dialog box
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}

/*----------Listener class to get coordinates ------------- */
private class MyLocationListener implements LocationListener {
@Override
public void onLocationChanged(Location loc) {

editLocation.setText("");
pb.setVisibility(View.INVISIBLE);
Toast.makeText(getBaseContext(),"Location changed : Lat: " +
loc.getLatitude()+ " Lng: " + loc.getLongitude(),
Toast.LENGTH_SHORT).show();
String longitude = "Longitude: " +loc.getLongitude();
Log.v(TAG, longitude);
String latitude = "Latitude: " +loc.getLatitude();
Log.v(TAG, latitude);

/*----------to get City-Name from coordinates ------------- */
String cityName=null;
Geocoder gcd = new Geocoder(getBaseContext(),
Locale.getDefault());
List<Address> addresses;
try {
addresses = gcd.getFromLocation(loc.getLatitude(), loc
.getLongitude(), 1);
if (addresses.size() > 0)
System.out.println(addresses.get(0).getLocality());
cityName=addresses.get(0).getLocality();
} catch (IOException e) {
e.printStackTrace();
}

String s = longitude+"\n"+latitude +
"\n\nMy Currrent City is: "+cityName;
editLocation.setText(s);
}

@Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}

@Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}

@Override
public void onStatusChanged(String provider,
int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
}
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
 xmlns:android="http://schemas.android.com/apk/res/android"
 android:orientation="vertical"
 android:layout_width="fill_parent"
 android:layout_height="fill_parent"
 android:weightSum="1">
 <TextView
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:text="Get Current Location and City Name"
  android:layout_weight="0.20"
  android:gravity="center"
  android:textSize="20sp" />
 <EditText
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:layout_weight="0.33"
  android:id="@+id/editTextLocation"
  android:editable="false">
  <requestFocus></requestFocus>
 </EditText>
 <LinearLayout
  android:id="@+id/layButtonH"
  android:layout_height="wrap_content"
  android:layout_width="fill_parent"
  android:gravity="center"
  android:layout_weight="0.15">
  <Button
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:text="Get Location"
   android:id="@+id/btnLocation"></Button>
 </LinearLayout>
 <LinearLayout
  android:id="@+id/layloadingH"
  android:layout_height="wrap_content"
  android:layout_weight="0.20"
  android:layout_width="fill_parent"
  android:gravity="center">
  <ProgressBar
   android:layout_width="wrap_content"
   android:id="@+id/progressBar1"
   android:layout_height="wrap_content"></ProgressBar>
 </LinearLayout>
</LinearLayout>

AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest
 xmlns:android="http://schemas.android.com/apk/res/android"
 package="com.rdc"
 android:versionCode="1"
 android:versionName="1.0">
 <uses-sdk android:minSdkVersion="10" />

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION">
</uses-permission>

 <application
  android:icon="@drawable/icon"
  android:label="@string/app_name">
  <activity
   android:name=".GetCurrentLocation"
   android:label="@string/app_name">
   <intent-filter>
   <action android:name="android.intent.action.MAIN" />
   <category android:name="android.intent.category.LAUNCHER" />
   </intent-filter>
  </activity>

 </application>
</manifest>

The output Screen will be like this..



Check if GPS/Network Provider Services are enabled or not?


How to check if GPS/Network Provider Services are enabled?


LocationManager lm = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
boolean gps_enabled = false;
boolean network_enabled = false;

try {
    gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
} catch(Exception ex) {}

try {
    network_enabled = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
} catch(Exception ex) {}

if(!gps_enabled && !network_enabled) {
    // notify user
 AlertDialog.Builder dialog = new AlertDialog.Builder(context);
 dialog.setMessage(context.getResources().getString(R.string.gps_network_not_enabled));
 dialog.setPositiveButton(context.getResources().getString(R.string.open_location_settings), 
new DialogInterface.OnClickListener() {
       @Override
       public void onClick(DialogInterface paramDialogInterface, int paramInt) {
           // TODO Auto-generated method stub
           Intent myIntent = new Intent( Settings.ACTION_LOCATION_SOURCE_SETTINGS);
           context.startActivity(myIntent);
             //get gps
            }
        });
    dialog.setNegativeButton(context.getString(R.string.Cancel), new DialogInterface.
OnClickListener()
   {

            @Override
            public void onClick(DialogInterface paramDialogInterface, int paramInt) {
                // TODO Auto-generated method stub

            }
        });
    dialog.show();      
}


Add below permissions in androidManifest.xml 

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>

//-----------------------------------------------------------------------
NOTE:-if you got any warning message like "Call requires permission which may be rejected
 by user. Code should explicitly check to see if permission is available." then you can 
try one by one of below step.


1) Ensure you have your permissions listed in the Manifest:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
(2) Ensure you use ContextCompat as this has compatibility with older API levels.
(3) In your location service, or class that initializes your LocationManager and gets the last known location, we need to check the permissions:
if ( Build.VERSION.SDK_INT >= 23 &&
             ContextCompat.checkSelfPermission( context, android.Manifest.permission.ACCESS_FINE_LOCATION ) != PackageManager.PERMISSION_GRANTED &&
             ContextCompat.checkSelfPermission( context, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return  ;
        }

(4) Ensure you request permissions from the user: 
if ( ContextCompat.checkSelfPermission( this, android.Manifest.permission.ACCESS_COARSE_
LOCATION ) != PackageManager.PERMISSION_GRANTED ) {

     ActivityCompat.requestPermissions( this, new String[] {  android.Manifest.permission.ACCESS_COARSE_LOCATION  },
                                                LocationService.MY_PERMISSION_ACCESS_COURSE_LOCATION );
 }