Requesting Location updates in oncreate method - android

I am trying to implement a location alarm kind of application.
But whenever my application opens. my current location shows as null.
Below is my code.
package com.hrupin;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class HelloAndroidGpsActivity extends Activity implements OnClickListener, android.content.DialogInterface.OnClickListener, LocationListener {
private TextView setLat, setLong, destLat, destLong, currLat, currLong, tjd, fromhome, toward;
private Button setmyLoc, setDest;
private EditText editLat, editLong;
private LocationManager orgManager;
//private LocationListener orgListener;
// private LocationListener destListener = new destListener();
private boolean gps_enabled = false;
private boolean network_enabled = false;
private String bestProvider;
double orginLongitude, orginLatitude, destLongtitude, destLatitude, currLatitude, currLongtitude;
float firstLat, firstLang, secLat, secLang;
Location destinationLocation = new Location("gps");
Location originLocation = new Location("gps");
Location currLocation = new Location("gps");
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
setLat = (TextView) findViewById(R.id.setLat);
setLong = (TextView) findViewById(R.id.setLong);
destLat = (TextView) findViewById(R.id.destLat);
destLong = (TextView) findViewById(R.id.destLong);
currLat = (TextView) findViewById(R.id.currLat);
currLong = (TextView)findViewById(R.id.currLong);
tjd = (TextView)findViewById(R.id.setmeter);
fromhome = (TextView)findViewById(R.id.destmeter);
toward = (TextView)findViewById(R.id.currmeter);
setDest = (Button)findViewById(R.id.SetLocation);
editLat = (EditText)findViewById(R.id.editLat);
editLong = (EditText)findViewById(R.id.editLong);
orgManager = (LocationManager)this.getSystemService(Context.LOCATION_SERVICE);
try {
gps_enabled = orgManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
} catch (Exception ex) {
Log.i("gps_enabled", ex.toString());
}
try {
network_enabled = orgManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
} catch (Exception ex) {
Log.i("network_enabled", ex.toString());
}
// don't start listeners if no provider is enabled
if (!gps_enabled && !network_enabled) {
AlertDialog.Builder builder = new Builder(
HelloAndroidGpsActivity.this);
builder.setTitle("Attention!");
builder.setMessage("Sorry, location is not determined. Please enable location providers");
builder.setPositiveButton("OK",
HelloAndroidGpsActivity.this);
builder.setNeutralButton("Cancel",
HelloAndroidGpsActivity.this);
builder.create().show();
}
Criteria criteria = new Criteria();
bestProvider = orgManager.getBestProvider(criteria, false);
orgManager.requestLocationUpdates(bestProvider, 0, 0, this);
Location location = orgManager.getLastKnownLocation(bestProvider);
if (location!=null){
setLat.setText("Latitude:" + currLatitude);
setLong.setText("Longitude:" + currLongtitude);
originLocation.setLatitude(currLatitude);
originLocation.setLongitude(currLongtitude);
}
//else Toast.makeText(getBaseContext(), "Error in GPS", Toast.LENGTH_SHORT).show();
setDest.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
destLat.setText("Lat:"+editLat.getText().toString().trim());
destLong.setText("Long"+editLong.getText().toString().trim());
destLatitude = Double.parseDouble(String.valueOf(editLat.getText().toString().trim()));
destLongtitude = Double.parseDouble(String.valueOf(editLong.getText().toString().trim()));
destinationLocation.setLatitude(destLatitude);
destinationLocation.setLongitude(destLongtitude);
float distance = originLocation.distanceTo(destinationLocation);
tjd.setText(String.valueOf(distance/1000)+ " Kms ");
}
});
}
/** Register for the updates when Activity is in foreground */
#Override
protected void onResume() {
super.onResume();
orgManager.requestLocationUpdates(bestProvider, 60000, 1, this);
}
/** Stop the updates when Activity is paused */
#Override
protected void onPause() {
super.onPause();
orgManager.removeUpdates(this);
}
public void onClick(DialogInterface dialog, int which) {
if (which == DialogInterface.BUTTON_NEUTRAL) {
setLat.setText("Sorry, location is not determined. To fix this please enable location providers");
} else if (which == DialogInterface.BUTTON_POSITIVE) {
startActivity(new Intent(
android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
}
}
public void onClick(View v) {
// TODO Auto-generated method stub
}
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
if (location != null) {
// This needs to stop getting the location data and save the
// battery power.
//orgManager.removeUpdates(orgListener);
currLatitude = location.getLatitude();
currLongtitude = location.getLongitude();
currLocation.setLatitude(currLatitude);
currLocation.setLongitude(currLongtitude);
currLat.setText(String.valueOf(currLatitude));
currLong.setText(String.valueOf(currLongtitude));
float fromhome = originLocation.distanceTo(currLocation);
float toward = currLocation.distanceTo(destinationLocation);
HelloAndroidGpsActivity.this.fromhome.setText(String.valueOf(fromhome/1000)+ " Kms ");
HelloAndroidGpsActivity.this.toward.setText(String.valueOf(toward/1000) + " Kms ");
if (toward/1000 <= 14 ){
Toast.makeText(getBaseContext(), "You are "+ toward/1000 + " Kms towards Destination ", Toast.LENGTH_SHORT).show();
}
}
}
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
I know this kind of question has been million times. I have tried all methods which has been specified in answers. But i havent got any output. Please help.

You should not call requestLocationUpdates on onCreate as it is redundant since your code will call it on onResume. The flow is onCreate --> onStart --> onResume.

To get Current Location, this is working pretty fine with me check this out.
our Activity is like this
public class MainActivity extends Activity implements OnClickListener, android.content.DialogInterface.OnClickListener {
/** Called when the activity is first created. */
private EditText showLocation;
private Button btnGetLocation;
private ProgressBar progress;
private LocationManager locManager;
private LocationListener locListener = new myLocationListener();
private boolean gps_enabled = false;
private boolean network_enabled = false;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
showLocation = (EditText) findViewById(R.id.txtShowLoc);
showLocation.setEnabled(false);
progress = (ProgressBar) findViewById(R.id.progressBar);
progress.setVisibility(View.GONE);
btnGetLocation = (Button) findViewById(R.id.btnGetLoc);
btnGetLocation.setOnClickListener(this);
locManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
progress.setVisibility(View.VISIBLE);
try{
gps_enabled = locManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
}
catch(Exception ex){
}
try{
network_enabled = locManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
}
catch(Exception ex){
}
if (!gps_enabled && !network_enabled) {
AlertDialog.Builder builder = new Builder(this);
builder.setTitle("Attention!");
builder.setMessage("Sorry, location is not determined. Please enable location providers");
builder.setPositiveButton("OK", this);
builder.setNeutralButton("Cancel", this);
builder.create().show();
progress.setVisibility(View.GONE);
}
if (gps_enabled) {
locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locListener);
}
if (network_enabled) {
locManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locListener);
}
}
private class myLocationListener implements LocationListener{
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
if(location!=null){
locManager.removeUpdates(locListener);
String Speed = "Device Speed: " +location.getSpeed();
String longitude = "Longitude: " +location.getLongitude();
String latitude = "Latitude: " +location.getLatitude();
String altitiude = "Altitiude: " + location.getAltitude();
String accuracy = "Accuracy: " + location.getAccuracy();
String time = "Time: " + location.getTime();
String cityName=null;
Geocoder gcd = new Geocoder(getBaseContext(), Locale.getDefault());
//public List<Address> addresses= gcd.getFromLocation (double latitude1, double longitude1, int maxResults)
List<Address> addresses;
try {
addresses = gcd.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
if (addresses.size() > 0)
System.out.println(addresses.get(0).getLocality());
cityName=addresses.get(0).getLocality();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
showLocation.setText("City Name: "+cityName+"\n"+Speed + "\n"+longitude + "\n" + latitude + "\n" + altitiude + "\n" + accuracy + "\n" + time);
progress.setVisibility(View.GONE);
}
}
#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
}
}
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
if(which == DialogInterface.BUTTON_NEUTRAL){
showLocation.setText("location is not getting due to location provider");
}
else if (which == DialogInterface.BUTTON_POSITIVE){
startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
}
}}
and main.xml is
<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:id="#+id/textView1" android:layout_width="match_parent" android:text="My Location is:" android:textSize="25sp" android:layout_height="wrap_content"></TextView>
<EditText android:layout_height="wrap_content" android:layout_width="match_parent" android:layout_weight="0.24" android:lines="5" android:id="#+id/txtShowLoc">
<requestFocus></requestFocus>
</EditText>
<LinearLayout android:id="#+id/linearLayout2" android:layout_height="wrap_content" android:layout_width="match_parent" android:gravity="center">
<ProgressBar android:layout_height="wrap_content" android:layout_width="wrap_content" android:id="#+id/progressBar"></ProgressBar>
</LinearLayout>
<LinearLayout android:id="#+id/linearLayout1" android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="center">
<Button android:layout_height="wrap_content" android:layout_width="wrap_content" android:text="Get Current Location" android:id="#+id/btnGetLoc"></Button>
</LinearLayout>
and my manifest file is
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="rdc.getCurrentLocaion"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="8" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission>
<application android:icon="#drawable/icon" android:label="#string/app_name" android:debuggable="true">
<activity android:name=".MainActivity"
android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
let me know if you get any trouble!!

#Ramdhan Thanks for your code. But i corrected a mistake made in my code.
Criteria criteria = new Criteria();
bestProvider = orgManager.getBestProvider(criteria, false);
orgManager.requestLocationUpdates(bestProvider, 0, 0, this);
Location location = orgManager.getLastKnownLocation(bestProvider);
if (location!=null){
setLat.setText("Latitude:" + currLatitude);
setLong.setText("Longitude:" + currLongtitude);
originLocation.setLatitude(currLatitude);
originLocation.setLongitude(currLongtitude);
}
Cheanged code:
if (location != null) {
setLat.setText("Latitude:" + location.getLatitude());
setLong.setText("Longitude:" + location.getLongitude());
originLocation.setLatitude(location.getLatitude());
originLocation.setLongitude(location.getLongitude());
}

Related

I m calculating distance between 2 points in map in real time as the user walks if destination is fixed

I m trying to calculate distance in real time between 2 co-ordinates as the user walks. I am using a while loop which hangs my application. I have no idea how to rectify it. Can anyone suggest a alternative to it.
package com.ankur.mapdemo;
import android.app.Activity;import android.app.Activity;
import android.app.NotificationManager;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
public class AlertReminder extends Activity implements OnCheckedChangeListener,LocationListener {
CheckBox cb1,cb2,cb3,cb4,cb5,cb6,cb7;
TextView tv1,tv2;
double currentlatitude=0,currentlongitude=0;
float dis = 0;
Location mostrecent = new Location("");
LocationManager locationManager;
LocationListener locationListener;
Context context;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.alertreminder);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
/*
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
// Called when a new location is found by the network location provider.
makeUseOfNewLocation(location);
}
public void onStatusChanged(String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) {}
public void onProviderDisabled(String provider) {}
};
*/
// Register the listener with the Location Manager to receive location updates
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1, 1, this);
tv2= (TextView)findViewById(R.id.location1);
tv1 = (TextView)findViewById(R.id.currentlocation);
cb1 = (CheckBox)findViewById(R.id.sjt);
cb1.setOnCheckedChangeListener(this);
cb2 = (CheckBox)findViewById(R.id.tt);
cb2.setOnCheckedChangeListener(this);
cb3 = (CheckBox)findViewById(R.id.smv);
cb3.setOnCheckedChangeListener(this);
cb4 = (CheckBox)findViewById(R.id.mb);
cb4.setOnCheckedChangeListener(this);
cb5 = (CheckBox)findViewById(R.id.gdn);
cb5.setOnCheckedChangeListener(this);
cb6 = (CheckBox)findViewById(R.id.cdmm);
cb6.setOnCheckedChangeListener(this);
cb7 = (CheckBox)findViewById(R.id.allmart);
cb7.setOnCheckedChangeListener(this);
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
currentlatitude = location.getLatitude();
currentlongitude = location.getLongitude();
makeuseofnewlocation(location);
//newlocation(location);
tv1.setText("Latitude:" + location.getLatitude() + ", Longitude:" + location.getLongitude() + ", Distance:" + dis);
}
private void makeuseofnewlocation(Location location1) {
// TODO Auto-generated method stub
mostrecent = location1;
//currentlatitude = location.getLatitude();
//currentlongitude = location.getLongitude();
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
Log.d("Latitude","disable");
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
Log.d("Latitude","enable");
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
Log.d("Latitude","status");
}
#Override
public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
// TODO Auto-generated method stub
int i = arg0.getId();
if(i == R.id.allmart)
{
if(arg1)
{
double destLat = 12.972887;
double destLong = 79.159715;
Location me = new Location("");
Location dest = new Location("");
me.setLatitude(currentlatitude);
me.setLongitude(currentlongitude);
dest.setLatitude(destLat);
dest.setLongitude(destLong);
float dist = me.distanceTo(dest);
while(dist > 50)
{
makeuseofnewlocation(mostrecent);
//cbskjcbkcb
//cbshbcbcbhchj
//currentlatitude = l1.getLatitude();
//currentlongitude = l1.getLongitude();
me.setLatitude(mostrecent.getLatitude());
me.setLongitude(mostrecent.getLongitude());
dest.setLatitude(destLat);
dest.setLongitude(destLong);
dist = me.distanceTo(dest);
dis = dist;
}
if(dist <= 50)
{
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
Uri soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(getApplicationContext())
.setSmallIcon(R.drawable.notify)
.setContentTitle("ALERT")
.setContentText("this is a notification")
.setSound(soundUri);
notificationManager.notify(0, mBuilder.build());
}
}
}
}
}
`
As long as the distance is greater than 50, it will stay inside the loop, but won't update anything in your layout. I would create a new thread for this calculation (google multithreading), and let your main thread only get those values and update them in your layout.

How to continuously show latitude and longitude in a Toast message?

I want to display latitude and longitude continuously in toast...
If user moves then lat long should be change... the following code only pops up lat long when it is installed it is not changing...
I want lat long without internet means only from GPS...
GPSTracker.java
package com.techblogon.serviceexample;
import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.util.Log;
public class GPSTracker extends Service implements LocationListener {
private final Context mContext;
// flag for GPS status
boolean isGPSEnabled = false;
// flag for network status
boolean isNetworkEnabled = false;
// flag for GPS status
boolean canGetLocation = false;
Location location; // location
double latitude; // latitude
double longitude; // longitude
// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 1; // 10 meters
// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 1; // 1 minute
// Declaring a Location Manager
protected LocationManager locationManager;
public GPSTracker(Context context) {
this.mContext = context;
getLocation();
}
public Location getLocation() {
try {
locationManager = (LocationManager) mContext
.getSystemService(LOCATION_SERVICE);
// getting GPS status
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
// no network provider is enabled
} else {
this.canGetLocation = true;
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network", "Network");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
// if GPS Enabled get lat/long using GPS Services
if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS Enabled", "GPS Enabled");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return location;
}
/**
* Stop using GPS listener
* Calling this function will stop using GPS in your app
* */
public void stopUsingGPS(){
if(locationManager != null){
locationManager.removeUpdates(GPSTracker.this);
}
}
/**
* Function to get latitude
* */
public double getLatitude(){
if(location != null){
latitude = location.getLatitude();
}
// return latitude
return latitude;
}
/**
* Function to get longitude
* */
public double getLongitude(){
if(location != null){
longitude = location.getLongitude();
}
// return longitude
return longitude;
}
/**
* Function to check GPS/wifi enabled
* #return boolean
* */
public boolean canGetLocation() {
return this.canGetLocation;
}
/**
* Function to show settings alert dialog
* On pressing Settings button will lauch Settings Options
* */
public void showSettingsAlert(){
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
// Setting Dialog Title
alertDialog.setTitle("GPS is settings");
// Setting Dialog Message
alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");
// On pressing Settings button
alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(intent);
}
});
// on pressing cancel button
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
}
#Override
public void onLocationChanged(Location location) {
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public IBinder onBind(Intent arg0) {
return null;
}
}
MyService.java
package com.techblogon.serviceexample;
import android.app.Service;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Handler;
import android.os.IBinder;
import android.preference.PreferenceManager;
import android.util.Log;
import android.widget.Toast;
public class MyService extends Service{
GPSTracker gps;
static int i=0;
private static final String TAG = "MyService";
#Override
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public void onCreate() {
Toast.makeText(this, "Congrats! MyService Created", Toast.LENGTH_SHORT).show();
Log.d(TAG, "onCreate");
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(MyService.this);
Editor editor = sharedPreferences.edit();
editor.putInt("key", 0);
editor.commit();
}
#Override
public void onStart(Intent intent, int startId) {
//Toast.makeText(this, "My Service Started", Toast.LENGTH_SHORT).show();
gps = new GPSTracker(MyService.this);
i=0;
Handler h = new Handler();
h.postDelayed(new Runnable()
{
public void run()
{
if(getI()==0)
{
latlong();
startService(new Intent(MyService.this,MyService.class));
}
}
}, 5000);
Log.d(TAG, "onStart");
}
#Override
public void onDestroy() {
i=1;
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(MyService.this);
Editor editor = sharedPreferences.edit();
editor.putInt("key", 1);
editor.commit();
Toast.makeText(this, "MyService Stopped", Toast.LENGTH_SHORT).show();
Log.d(TAG, "onDestroy");
}
public int getI()
{
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
return sharedPreferences.getInt("key",0);
}
public void latlong()
{
if(gps.canGetLocation()){
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_SHORT).show();
}else{
// can't get location
// GPS or Network is not enabled
// Ask user to enable GPS/network in settings
gps.showSettingsAlert();
}
}
}
MainActivity.java
package com.techblogon.serviceexample;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
//start the service
public void onClickStartServie(View V)
{
//start the service from here //MyService is your service class name
startService(new Intent(this, MyService.class));
}
//Stop the started service
public void onClickStopService(View V)
{
//Stop the running service from here//MyService is your service class name
//Service will only stop if it is already running.
stopService(new Intent(this, MyService.class));
}
}
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<TextView
android:id="#+id/text_view_header"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:textColor="#FF0000"
android:textSize="20sp"
android:text=" " />
<Button
android:id="#+id/start_service"
android:layout_marginTop="20dp"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:text="Start Service"
android:layout_below="#+id/text_view_header"
android:onClick="onClickStartServie" />
<Button
android:id="#+id/stop_service"
android:layout_marginTop="20dp"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:text="Stop Service"
android:layout_below="#+id/start_service"
android:onClick="onClickStopService" />
</RelativeLayout>
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.techblogon.serviceexample"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="16" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.techblogon.serviceexample.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:enabled="true" android:name=".MyService" />
</application>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
</manifest>
Please give me the code where i need to change....????
Use your LocationManager to set the refresh rate of your location:
LocationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Then, inside your onLocationChanged(Location l) method, post the Toast message:
#Override
public void onLocationChanged(Location location) {
Toast.makeText(getApplicationContext(), "Long: " + location.getLongitude() + ", Lat: " + location.getLatitude(), Toast.LENGTH_SHORT).show();
}
This will fire a Toast message everytime the location of the user changes.

Using AsyncTask to get location information

I'm trying to get user's current location coordinates and address using reverse geocoding.
As This process takes some time, I want to show a progress bar during that time, so I'm using AsyncTask. So, what basically I'm doing is, from one activity's onClick event I start the AsyncTask which finds me the location informations and then from that AsyncTask I start another activity which uses that Information.
This is my First Activity where onClick event starts the AsyncTask:
public void onClickGirl(View view)
{
(new MyAsyncTask(MainActivity.this)).execute();
}
This is the AsyncTask:
public class MyAsyncTask extends AsyncTask<Void, Void, Void> implements LocationListener {
private Context ContextAsync;
public MyAsyncTask (Context context){
this.ContextAsync = context.getApplicationContext();
}
Dialog progress;
private String providerAsync;
private LocationManager locationManagerAsync;
double latAsync=0.0;
double lonAsync=0.0;
String thikanaAsync="Scan sms for location";
String AddressAsync="";
Geocoder GeocoderAsync;
#Override
protected void onPreExecute() {
super.onPreExecute();
progress = ProgressDialog.show(null, "Loading data", "Please wait...");
}
#Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
locationManagerAsync = (LocationManager) ContextAsync.getSystemService(ContextAsync.LOCATION_SERVICE);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_COARSE);
criteria.setCostAllowed(false);
criteria.setPowerRequirement(Criteria.NO_REQUIREMENT);
providerAsync = locationManagerAsync.getBestProvider(criteria, false);
if (locationManagerAsync.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
providerAsync = LocationManager.GPS_PROVIDER;
} else if (locationManagerAsync.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
providerAsync = LocationManager.NETWORK_PROVIDER;
/*AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("GPS is disabled in the settings!");
alert.setMessage("It is recomended that you turn on your device's GPS and restart the app so the app can determine your location more accurately!");
alert.setPositiveButton("OK", null);
alert.show();*/
} else if (locationManagerAsync.isProviderEnabled(LocationManager.PASSIVE_PROVIDER)) {
providerAsync = LocationManager.PASSIVE_PROVIDER;
Toast.makeText(ContextAsync, "Switch On Data Connection!!!!", Toast.LENGTH_LONG).show();
}
Location location = locationManagerAsync.getLastKnownLocation(providerAsync);
// Initialize the location fields
if (location != null) {
// System.out.println("Provider " + provider + " has been selected.");
latAsync = location.getLatitude();
lonAsync = location.getLongitude();
onLocationChanged(location);
} else {
Toast.makeText(ContextAsync, " Locationnot available", Toast.LENGTH_SHORT).show();
}
List<Address> addresses = null;
GeocoderAsync = new Geocoder(ContextAsync, Locale.getDefault());
try {
addresses = GeocoderAsync.getFromLocation(latAsync, lonAsync, 1);
String address = addresses.get(0).getAddressLine(0);
String city = addresses.get(0).getAddressLine(1);
String country = addresses.get(0).getCountryName();
AddressAsync = Html.fromHtml(
address + ", " + city + ",<br>" + country).toString();
} catch (Exception e) {
e.printStackTrace();
AddressAsync = "Refresh for the address";
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
progress.dismiss();
Intent intentAsync = new Intent(ContextAsync,Emerg.class);
intentAsync.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intentAsync.putExtra("calculated_Lat", latAsync);
intentAsync.putExtra("calculated_Lon", lonAsync);
intentAsync.putExtra("calculated_address", AddressAsync);
ContextAsync.startActivity(intentAsync);
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
locationManagerAsync.requestLocationUpdates(providerAsync, 0, 0, this);
}
#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
}
}
This is the Second Activity which run after AsyncTask:`
Intent ixx = getIntent();
elat = Double.parseDouble(ixx.getStringExtra("calculated_Lat"));
elon = Double.parseDouble(ixx.getStringExtra("calculated_Lon"));
eAddress1 = ixx.getStringExtra("calculated_address");
And This is the LogCat:
02-01 17:15:26.734: E/AndroidRuntime(2587): java.lang.IllegalStateException: Could not execute method of the activity
02-01 17:15:26.734: E/AndroidRuntime(2587): at android.view.View$1.onClick(View.java:3814)
02-01 17:15:26.734: E/AndroidRuntime(2587): at android.view.View.performClick(View.java:4424)
02-01 17:15:26.734: E/AndroidRuntime(2587): at android.os.Handler.handleCallback(Handler.java:733)
02-01 17:15:26.734: E/AndroidRuntime(2587): at android.os.Handler.dispatchMessage(Handler.java:95)
02-01 17:15:26.734: E/AndroidRuntime(2587): at android.os.Looper.loop(Looper.java:137)
I have spent hours after this but can't find the problem. Can anyone please help me finding out what I'm missing??
Please find the updated code and test it at your end and let me know in case you have any query:
package com.example.tabhost;
import java.util.List;
import java.util.Locale;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Html;
import android.util.Log;
public class MyAsyncTask extends AsyncTask<Void, Void, Void> implements LocationListener {
private Context ContextAsync;
public MyAsyncTask (Context context){
this.ContextAsync = context;
}
Dialog progress;
private String providerAsync;
private LocationManager locationManagerAsync;
double latAsync=0.0;
double lonAsync=0.0;
String thikanaAsync="Scan sms for location";
String AddressAsync="";
Geocoder GeocoderAsync;
Location location;
#Override
protected void onPreExecute() {
super.onPreExecute();
progress = ProgressDialog.show(ContextAsync, "Loading data", "Please wait...");
}
#Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
locationManagerAsync = (LocationManager) ContextAsync.getSystemService(ContextAsync.LOCATION_SERVICE);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_COARSE);
criteria.setCostAllowed(false);
criteria.setPowerRequirement(Criteria.NO_REQUIREMENT);
providerAsync = locationManagerAsync.getBestProvider(criteria, false);
if (locationManagerAsync.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
providerAsync = LocationManager.GPS_PROVIDER;
} else if (locationManagerAsync.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
providerAsync = LocationManager.NETWORK_PROVIDER;
/*AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("GPS is disabled in the settings!");
alert.setMessage("It is recomended that you turn on your device's GPS and restart the app so the app can determine your location more accurately!");
alert.setPositiveButton("OK", null);
alert.show();*/
} else if (locationManagerAsync.isProviderEnabled(LocationManager.PASSIVE_PROVIDER)) {
providerAsync = LocationManager.PASSIVE_PROVIDER;
//Toast.makeText(ContextAsync, "Switch On Data Connection!!!!", Toast.LENGTH_LONG).show();
}
location = locationManagerAsync.getLastKnownLocation(providerAsync);
// Initialize the location fields
if (location != null) {
// System.out.println("Provider " + provider + " has been selected.");
latAsync = location.getLatitude();
lonAsync = location.getLongitude();
} else {
//Toast.makeText(ContextAsync, " Locationnot available", Toast.LENGTH_SHORT).show();
}
List<Address> addresses = null;
GeocoderAsync = new Geocoder(ContextAsync, Locale.getDefault());
try {
addresses = GeocoderAsync.getFromLocation(latAsync, lonAsync, 1);
String address = addresses.get(0).getAddressLine(0);
String city = addresses.get(0).getAddressLine(1);
String country = addresses.get(0).getCountryName();
AddressAsync = Html.fromHtml(
address + ", " + city + ",<br>" + country).toString();
} catch (Exception e) {
e.printStackTrace();
AddressAsync = "Refresh for the address";
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
progress.dismiss();
onLocationChanged(location);
Log.v("latAsync_lonAsync",latAsync+"_"+lonAsync);
Intent intentAsync = new Intent(ContextAsync,Emerg.class);
intentAsync.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intentAsync.putExtra("calculated_Lat", latAsync);
intentAsync.putExtra("calculated_Lon", lonAsync);
intentAsync.putExtra("calculated_address", AddressAsync);
ContextAsync.startActivity(intentAsync);
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
locationManagerAsync.requestLocationUpdates(providerAsync, 0, 0, this);
}
#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
}
}
instead of using this.ContextAsync = context.getApplicationContext();
ContextAsync should have Activity instance, no ApplicationContext so use this.ContextAsync = context

how I can get the city name of my current position?

I'm working with android studio and in a popup dialog I want that users can get their position but all I know to do is get my latitude and longitude.
This is the code
import android.app.Activity;
import android.content.Context;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity implements LocationListener {
private TextView latituteField;
private TextView longitudeField;
private LocationManager locationManager;
private String provider;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
latituteField = (TextView) findViewById(R.id.TextView02);
longitudeField = (TextView) findViewById(R.id.TextView04);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);
if (location != null) {
System.out.println("Provider " + provider + " has been selected.");
onLocationChanged(location);
} else {
latituteField.setText("Location not available");
longitudeField.setText("Location not available");
}
}
#Override
protected void onResume() {
super.onResume();
locationManager.requestLocationUpdates(provider, 400, 1, this);
}
#Override
protected void onPause() {
super.onPause();
locationManager.removeUpdates(this);
}
#Override
public void onLocationChanged(Location location) {
int lat = (int) (location.getLatitude());
int lng = (int) (location.getLongitude());
latituteField.setText(String.valueOf(lat));
longitudeField.setText(String.valueOf(lng));
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
Toast.makeText(this, "Enabled new provider " + provider,
Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderDisabled(String provider) {
Toast.makeText(this, "Disabled provider " + provider,
Toast.LENGTH_SHORT).show();
}
}
in the MainActivity.Can you help me?
I've added this in the manifest
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION"/>
but it still says "Location not available".
You need the GeoCoder class to get Address from a given Lat/Long. try the following:
Geocoder geoCoder = new Geocoder(this, Locale.getDefault()); //it is Geocoder
StringBuilder builder = new StringBuilder();
try {
List<Address> address = geoCoder.getFromLocation(latitude, longitude, 1);
int maxLines = address.get(0).getMaxAddressLineIndex();
for (int i=0; i<maxLines; i++) {
String addressStr = address.get(0).getAddressLine(i);
builder.append(addressStr);
builder.append(" ");
}
String fnialAddress = builder.toString(); //This is the complete address.
} catch (IOException e) {}
catch (NullPointerException e) {}
Code below should work for you: (Check the inline comments regarding your code)
import java.io.IOException;
import java.util.List;
import java.util.Locale;
import android.app.Activity;
import android.content.Context;
import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity implements LocationListener {
private TextView latituteField;
private TextView longitudeField;
private TextView addressField; //Add a new TextView to your activity_main to display the address
private LocationManager locationManager;
private String provider;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
latituteField = (TextView) findViewById(R.id.TextView02);
longitudeField = (TextView) findViewById(R.id.TextView04);
addressField = (TextView) findViewById(R.id.TextView05); //Make sure you add this to activity_main
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);
if (location != null) {
System.out.println("Provider " + provider + " has been selected.");
onLocationChanged(location);
} else {
latituteField.setText("Location not available");
longitudeField.setText("Location not available");
}
}
#Override
protected void onResume() {
super.onResume();
locationManager.requestLocationUpdates(provider, 400, 1, this);
}
#Override
protected void onPause() {
super.onPause();
locationManager.removeUpdates(this);
}
#Override
public void onLocationChanged(Location location) {
//You had this as int. It is advised to have Lat/Loing as double.
double lat = location.getLatitude();
double lng = location.getLongitude();
Geocoder geoCoder = new Geocoder(this, Locale.getDefault());
StringBuilder builder = new StringBuilder();
try {
List<Address> address = geoCoder.getFromLocation(lat, lng, 1);
int maxLines = address.get(0).getMaxAddressLineIndex();
for (int i=0; i<maxLines; i++) {
String addressStr = address.get(0).getAddressLine(i);
builder.append(addressStr);
builder.append(" ");
}
String fnialAddress = builder.toString(); //This is the complete address.
latituteField.setText(String.valueOf(lat));
longitudeField.setText(String.valueOf(lng));
addressField.setText(fnialAddress); //This will display the final address.
} catch (IOException e) {
// Handle IOException
} catch (NullPointerException e) {
// Handle NullPointerException
}
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
Toast.makeText(this, "Enabled new provider " + provider,
Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderDisabled(String provider) {
Toast.makeText(this, "Disabled provider " + provider,
Toast.LENGTH_SHORT).show();
}
}
You need to execute the Geocoder in a AsyncTask (or in a Thread not in the same ThreadGroup as the UI Thread)!
public void getCityName(final Location location, final OnGeocoderFinishedListener listener) {
new AsyncTask<Void, Integer, List<Address>>() {
#Override
protected List<Address> doInBackground(Void... arg0) {
Geocoder coder = new Geocoder(getContext(), Locale.ENGLISH);
List<Address> results = null;
try {
results = coder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
} catch (IOException e) {
// nothing
}
return results;
}
#Override
protected void onPostExecute(List<Address> results) {
if (results != null && listener != null) {
listener.onFinished(results);
}
}
}.execute();
}
With this abstract Listener
public abstract class OnGeocoderFinishedListener {
public abstract void onFinished(List<Address> results);
}
Now call the method like this:
getCityName(location, new OnGeocoderFinishedListener() {
#Override
public void onFinished(List<Address> results) {
// do something with the result
}
});
Hope this will help some of you!
You can use google api to get current location address. Check out my answer in this post go get your city.
How to get city name from latitude and longitude coordinates in Google Maps?

Android - get country via GPS errors

Hello StackOverflow :)
I have created some code inside my onStart(); method to ensure that the user has GPS enabled so i can figure out in which country is he right now. If GPS is disabled, it should show an alert dialog prompting the user to enable GPS before using the app.
For some reason, it seems like that whole chunk of code isn't working. I have disabled GPS and nothing is happening, no dialog and nothing like that. Why is this happening?
Here is my code:
#Override
protected void onStart() {
super.onStart();
LocationManager locationManager =
(LocationManager) getSystemService(Context.LOCATION_SERVICE);
final boolean gpsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
Location loc = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
Geocoder code = new Geocoder(TipCalculatorActivity.this);
try {
Address adr = (Address) code.getFromLocation(loc.getLatitude(), loc.getLongitude(), 1);
CountryName = adr.getCountryCode();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (!gpsEnabled) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("This application requires GPS connectivity to determine your current country, and deliver you accurate tip ratings. Do you wish to turn GPS on?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
TipCalculatorActivity.this.enableLocationSettings();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
TipCalculatorActivity.this.finish();
System.exit(1);
}
});
AlertDialog alert = builder.create();
alert.show();
}
}
private void enableLocationSettings() {
Intent settingsIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(settingsIntent);
}
Thanks a lot for any help :)
Location loc = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
Is may be returning null in your case since your mobile has no cached locations.
So change your code to
if (loc != null) {
Geocoder code = new Geocoder(AbcActivity.this);
try {
Address adr = (Address) code.getFromLocation(loc.getLatitude(), loc.getLongitude(), 1);
// CountryName = adr.getCountryCode();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
If you need to query current Location.Then you need to have active Data connection or GPS turned on.
Following Snippet will help you
import android.app.Activity;
import android.content.Context;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;
public class ShowLocationActivity extends Activity implements LocationListener {
private TextView latituteField;
private TextView longitudeField;
private LocationManager locationManager;
private String provider;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
latituteField = (TextView) findViewById(R.id.TextView02);
longitudeField = (TextView) findViewById(R.id.TextView04);
// Get the location manager
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// Define the criteria how to select the locatioin provider -> use
// default
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);
// Initialize the location fields
if (location != null) {
System.out.println("Provider " + provider + " has been selected.");
int lat = (int) (location.getLatitude());
int lng = (int) (location.getLongitude());
latituteField.setText(String.valueOf(lat));
longitudeField.setText(String.valueOf(lng));
} else {
latituteField.setText("Provider not available");
longitudeField.setText("Provider not available");
}
}
/* Request updates at startup */
#Override
protected void onResume() {
super.onResume();
locationManager.requestLocationUpdates(provider, 400, 1, this);
}
/* Remove the locationlistener updates when Activity is paused */
#Override
protected void onPause() {
super.onPause();
locationManager.removeUpdates(this);
}
#Override
public void onLocationChanged(Location location) {
int lat = (int) (location.getLatitude());
int lng = (int) (location.getLongitude());
latituteField.setText(String.valueOf(lat));
longitudeField.setText(String.valueOf(lng));
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
Toast.makeText(this, "Enabled new provider " + provider,
Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderDisabled(String provider) {
Toast.makeText(this, "Disabled provider " + provider,
Toast.LENGTH_SHORT).show();
}
}
Finally make sure you have added following permissions.
< uses - permission android: name = "android.permission.ACCESS_FINE_LOCATION" / >
< uses - permission android: name = "android.permission.ACCESS_COARSE_LOCATION" / >

Categories

Resources