I am trying to get the latitude and longitude of my phone, and send those location details to an email address. It's working, but I'm not be able to get the exact longitude and latitude of my current location. I do not want to use the map view, I am trying to use GPS but I am not able to use it properly. This is my code:
package com.example.mapq;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class MapActivity extends Activity implements LocationListener{
LocationManager lm;
TextView lt, ln;
Button b1;
String provider;
Location l;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
ln=(TextView)findViewById(R.id.lng);
lt=(TextView)findViewById(R.id.lat);
b1=(Button) findViewById(R.id.button1);
lm=(LocationManager)this.getSystemService(Context.LOCATION_SERVICE);
Criteria c=new Criteria();
//criteria object will select best service based on
//Accuracy, power consumption, response, bearing and monetary cost
//set false to use best service otherwise it will select the default Sim network
//and give the location based on sim network
//now it will first check satellite than Internet than Sim network location
provider=lm.getBestProvider(c, false);
//now you have best provider
//get location
l=lm.getLastKnownLocation(provider);
if(l!=null)
{
//get latitude and longitude of the location
final double lng=l.getLongitude();
final double lat=l.getLatitude();
//display on text view
ln.setText(""+lng);
lt.setText(""+lat);
b1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent emailIntent = new Intent(Intent.ACTION_SEND);
emailIntent.putExtra(Intent.EXTRA_EMAIL, new String[]{"mallikarjuna8511820#gmail.com"});
emailIntent.putExtra(Intent.EXTRA_CC, new String[]{"mallikarjuna8511820#gmail.com"});
emailIntent.putExtra(Intent.EXTRA_SUBJECT, "subject");
emailIntent.putExtra(Intent.EXTRA_TEXT, "body");
emailIntent.putExtra(android.content.Intent.EXTRA_TEXT,
"http://maps.google.com/maps?q=loc:" + lat +","+ lng);
emailIntent.setType("plain/text");
startActivity(Intent.createChooser(emailIntent, "choose email client..."));
}
});
}
else
{
ln.setText("No Provider");
lt.setText("No Provider");
}
}
//If you want location on changing place also than use below method
//otherwise remove all below methods and don't implement location listener
#Override
public void onLocationChanged(Location arg0)
{
double lng=l.getLongitude();
double lat=l.getLatitude();
ln.setText(""+lng);
lt.setText(""+lat);
}
#Override
public void onProviderDisabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
// TODO Auto-generated method stub
}
}
You need to requestLocationUpdates somewhere in your code like onCreate/Resume like:
lm = (LocationManager) getSystemService(LOCATION_SERVICE);
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER,
mUpdatePeriod * 1000, mMinResendDistance, this);
where typical values might be:
private float mMinResendDistance = 10.0f;
private int mUpdatePeriod; // in SECONDS
.
Related
I am a newbie to Codename One and I am trying to invoke Native Interface from StateMachine.java and get some values back from the Native Interface Implementation. How do I do it?
Here are the codes of StateMachine.java and the Native Interface Implementation, NativeAndroidImpl.java
I want to call NativeAndroidImpl.java from StateMachine.java and get the longitude and latitude values from NativeAndroidImpl.java
----------------------------StateMachine.java----------------------------
#Override
protected void onMain_MainHelpButtonAction(Component c, ActionEvent event) {
Vector<String> vec = (Vector<String>)Storage.getInstance().readObject("SavedData");
//Invoke NativeAndroidImpl.java
double lat=//get latitude from NativeAndroidImpl.java
double lng=//get longitude from NativeAndroidImpl.java
try {
Display.getInstance().sendSMS(vec.elementAt(2), "I am in trouble. Send HELP! My location: http://maps.google.com/?q=" + lat + "," + lng, true);
} catch (IOException ex) {
Dialog.show("Error!", "Failed to send SMS.", "OK", null);
ex.printStackTrace();
}
}
}
------------------------NativeAndroidImpl.java--------------------------
package com.anonymous.emergencyhelp;
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.provider.Settings;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class NativeAndroidImpl {
LocationManager locationManager;
double longitudeNetwork, latitudeNetwork;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
}
private boolean checkLocation() {
if(!isLocationEnabled())
showAlert();
return isLocationEnabled();
}
private void showAlert() {
final AlertDialog.Builder dialog = new AlertDialog.Builder(this);
dialog.setTitle("Enable Location")
.setMessage("Your Locations Settings is set to 'Off'.\nPlease Enable Location to use this app")
.setPositiveButton("Location Settings", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
Intent myIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(myIntent);
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
}
});
dialog.show();
}
private boolean isLocationEnabled() {
return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) ||
locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
}
public void toggleNetworkUpdates(View view) {
if(!checkLocation())
return;
Button button = (Button) view;
if(button.getText().equals("Help"))
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 60 * 1000, 10, locationListenerNetwork);
}
private final LocationListener locationListenerNetwork = new LocationListener() {
public void onLocationChanged(Location location) {
longitudeNetwork = location.getLongitude();
latitudeNetwork = location.getLatitude();
runOnUiThread(new Runnable() {
#Override
public void run() {
//Send longitude and latitude values to StateMachine.java
Toast.makeText(MainActivity.this, "Network Provider update", Toast.LENGTH_SHORT).show();
}
});
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
};
public boolean isSupported() {
return true;
}
}
Check out this tutorial for using native interfaces.
Notice that you don't need native interfaces for location since a cross platform location API exists in Codename One. I suggest checking out the developer guide and tutorials for Codename One.
I'm really sorry ahead of time, but this question is pretty lengthy.
I have a functioning GPSTracker class that contains the means of pinging GPS Location for a device. In my MainActivity, I have a button that uses the GPS tracker to display the location in a toast. I'm trying to convert this button into an automatic action to be repeated every X minutes, let's go with 10.(Right now the alarm receiver is setup for 10 seconds)
Even when the app is in the background. So I set up an AlarmReceiver to try to do this, but I can't quite get it working.
Here's my GPSTracker class:
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;
public class GPSTracker extends Service implements LocationListener {
private final Context context;
boolean isGPSEnabled = false;
boolean canGetLocation = false;
boolean isNetworkEnabled = false;
Location location;
double latitude;
double longitude;
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10;
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1;
protected LocationManager locationManager;
public GPSTracker(Context context) {
this.context = context.getApplicationContext();
getLocation();
}
public Location getLocation(){
try {
locationManager = (LocationManager) context.getSystemService(LOCATION_SERVICE);
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if(!isGPSEnabled && !isNetworkEnabled) {
}else {
this.canGetLocation = true;
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
if(locationManager != null){
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if(location !=null){
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
if(isGPSEnabled){
if(location == null){
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
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;
}
public void stopUsingGPS() {
if(locationManager != null){
locationManager.removeUpdates(GPSTracker.this);
}
}
public double getLatitude() {
if(location!= null){
latitude = location.getLatitude();
}
return latitude;
}
public double getLongitude() {
if(location !=null){
longitude = location.getLongitude();
}
return longitude;
}
public boolean canGetLocation(){
return this.canGetLocation;
}
public void showSettingsAlert() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);
alertDialog.setTitle("GPS is settings");
alertDialog.setMessage("GPS isn't enabled. Do you want to go to settings menu?");
alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
context.startActivity(intent);
}
});
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int i) {
dialog.cancel();
}
});
alertDialog.show();
}
#Override
public void onLocationChanged(Location location) {
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
And here's my MainActivity:
package com.example.gwyn.locationnabtest;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
public class MainActivity extends ActionBarActivity {
Button btnShowLocation;
Button btnStartService;
Button btnStopService;
GPSTracker gps;
//GoogleMap mMap;
private PendingIntent pendingIntent;
private AlarmManager manager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnShowLocation = (Button) findViewById(R.id.show_location);
btnShowLocation.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
FragmentActivity activity = (FragmentActivity)view.getContext();
FragmentManager manager = activity.getSupportFragmentManager();
//MapFragment myMap = (MapFragment) (MainActivity.getFragmentManager()).findFragmentById((R.id.mapFragment));
// Test, remove me.
// mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.mapFragment)).getMap();
gps = new GPSTracker(MainActivity.this);
if(gps.canGetLocation()) {
// Location Achieved.
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
// Draw Marker for Current Location on Fragment
// Currently Crashing App
// mMap.addMarker(new MarkerOptions().position(new LatLng(latitude, longitude)).title("Marker"));
// Toast a popup of the location data.
Toast.makeText(getApplicationContext(), "Your Location is -\nLat:" + latitude + "\nLong:" + longitude, Toast.LENGTH_LONG).show();
} else {
gps.showSettingsAlert();
}
}
});
Intent alarmIntent = new Intent(this, AlarmReceiver.class);
pendingIntent = PendingIntent.getBroadcast(this, 0, alarmIntent, 0);
btnStartService = (Button) findViewById(R.id.start_service);
btnStartService.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
manager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
int interval = 10000;
// 10 Second Interval. Good for testing, but turn this off.
manager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), interval, pendingIntent);
Toast.makeText(getApplicationContext(), "Service Started", Toast.LENGTH_SHORT).show();
//startService(new Intent(getBaseContext(), MyServices.class));
}
});
btnStopService = (Button) findViewById(R.id.stop_service);
btnStopService.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Cancel pending intents
manager.cancel(pendingIntent);
Toast.makeText(getApplicationContext(), "Pending Intents Cancelled", Toast.LENGTH_SHORT).show();
}
});
}
}
To highlight specifically, this is the part in MainActivity that works to display the GPS:
public void onClick(View view) {
FragmentActivity activity = (FragmentActivity)view.getContext();
FragmentManager manager = activity.getSupportFragmentManager();
//MapFragment myMap = (MapFragment) (MainActivity.getFragmentManager()).findFragmentById((R.id.mapFragment));
// Test, remove me.
// mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.mapFragment)).getMap();
gps = new GPSTracker(MainActivity.this);
if(gps.canGetLocation()) {
// Location Achieved.
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
// Draw Marker for Current Location on Fragment
// Currently Crashing App
// mMap.addMarker(new MarkerOptions().position(new LatLng(latitude, longitude)).title("Marker"));
// Toast a popup of the location data.
Toast.makeText(getApplicationContext(), "Your Location is -\nLat:" + latitude + "\nLong:" + longitude, Toast.LENGTH_LONG).show();
} else {
gps.showSettingsAlert();
}
}
My AlarmReceiver is as follows, and produces an error when creating the GPSTracker:
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
public class AlarmReceiver extends BroadcastReceiver {
GPSTracker gps;
#Override
public void onReceive(Context arg0, Intent arg1) {
// Here's where we'd grab location and store it into DB.
//gps = new GPSTracker(AlarmReceiver.this);
// if(gps.canGetLocation()) {
// double latitude = gps.getLatitude();
// double longitude = gps.getLongitude();
// Draw Marker for Current Location on Fragment
// Toast a popup of the location data.
// Toast.makeText(arg0, "Your Location is -\nLat:" + latitude + "\nLong:" + longitude, Toast.LENGTH_LONG).show();
// } else {
// gps.showSettingsAlert();
// }
// Toast that the alarm ran.
Toast.makeText(arg0, "Location Pinged.", Toast.LENGTH_SHORT).show();
}
More specifically, a part of the problem is the way I'm calling for the new gps Tracker object here:
//gps = new GPSTracker(AlarmReceiver.this);
I'm not sure how to achieve the original result while using the alarmreceiver instead of a button, which is the main source of my problem. Does anyone know exactly what I can tinker with here to get the alarm receiver to properly use the GPSTracker Class?
DO not use GPSTracker. Its broken in over a dozen ways. Forget it exists. If you want a better version, you can use http://gabesechansoftware.com/location-tracking/ That link also explains why GPSTracker is broken by design and why it should never be used. It basically kinda works if used in optimal circumstances, and gives you horrible data in all the others.
Secondly, if you're using GPS and not network- you need to give it time to get a location sync. This can take seconds to minutes (or hours, if the user is in a basement or something) so the immediate forms of getting a location won't work- you have to wait for it to actually sync the location.
I suggest you not look for libraries to solve this and actually try to understand how the base APIs work. Until you do, you're going to have troubles with anything you use as there's lots of corner cases here and its not a trivial thing to do.
I just want to know why that code gives me a lot of markers at the same place when I try to
get users current location ?
I didn't manage to do that in a different class service if anyone knows how to do that in a service or AsyncTask that will help me a lot in my project.
Thanks!
package toutel.testcarte;
import org.osmdroid.ResourceProxy;
import org.osmdroid.bonuspack.overlays.Marker;
import org.osmdroid.tileprovider.tilesource.TileSourceFactory;
import org.osmdroid.util.GeoPoint;
import org.osmdroid.views.MapController;
import org.osmdroid.views.MapView;
import org.osmdroid.views.overlay.ItemizedOverlay;
import org.osmdroid.views.overlay.OverlayItem;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
public class MainActivity extends Activity {
private MapController mapController;
private MapView mapView;
private GeoPoint myposition;
private ItemizedOverlay<OverlayItem> mMyLocationOverlay;
private ResourceProxy mResourceProxy;
#SuppressLint("NewApi")
#SuppressWarnings("deprecation")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mapView = (MapView) findViewById(R.id.mapview);
mapController = (MapController) mapView.getController();
GeoPoint myposition = new GeoPoint(48.856614, 2.3522219000000177);
mapView.setTileSource(TileSourceFactory.MAPNIK);
mapView.setBuiltInZoomControls(false);
mapView.setMultiTouchControls(true);
// mapController.animateTo(myposition);
mapController.setZoom(13);
mapController.setCenter(myposition);
Context context = getApplicationContext();
CharSequence text = "Activez votre GPS pour utiliser la localisation ";
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem menu) {
switch (menu.getItemId()) {
case (R.id.fermer): {
System.exit(0);
break;
}
case (R.id.position): {
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
while (true) {
LocationListener mylocationlistener = new LocationListener() {
public void onLocationChanged(Location location) {
Context ctx = getApplicationContext();
GeoPoint myposition = new GeoPoint(
location.getLatitude(), location.getLongitude());
mapController.animateTo(myposition);
mapController.setCenter(myposition);
mapController.setZoom(17);
Marker marker = new Marker(mapView);
marker.setPosition(myposition);
marker.setAnchor(Marker.ANCHOR_CENTER,
Marker.ANCHOR_BOTTOM);
mapView.getOverlays().add(marker);
mapView.invalidate();
try {
Thread.sleep(10 * 1000);
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
#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
}
};
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 10000, 0, mylocationlistener);
break;
}
}
case (R.id.itineraire): {
}
}
return false;
}
}
Multiple markers : why?
You are getting multiple markers because every time location is changed you are placing a marker on the map.even change in the position is too small.You are placing marker.Try to zoom in you will see that all markers are not at same position.
My suggestion there is no need of service here.Because OnlocationChanged listener automatically do your job.I have written this single class.Now where ever in the project you need the GPS coordinates, just instantiate the class object and get the Latitude and Longitude.
LocationSender loc = new LocationSender(YourClass.this);
As i declared lat,lng (in LocationSender.java) as static so i can get any where its values.
double latitude = LocationSender.lat;
double longitude = LocationSender.lng;
LocationSender.java
public class LocationSender {
Context context;
LocationManager locationManager;
Location location;
static double lat,lng;
public LocationSender(Context ctx) {
context=ctx;
locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
}
// Acquire a reference to the system Location Manager
public void getNewLocation(Location location) throws JSONException
{
String latLongString = "";
if (location != null) {
this.location=location;
lat= location.getLatitude();
lng = location.getLongitude();
latLongString = "Lat:" + String.valueOf(LocationActivity.lat) + "\nLong:" + String.valueOf(LocationActivity.lng);
Log.d("Location Found", latLongString);
} else
{
location=null;
latLongString = "No location found";
}
Toast.makeText(context, latLongString, Toast.LENGTH_LONG).show();
}
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
// Called when a new location is found by the network location provider.
try {
getNewLocation(location);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void onProviderEnabled(String provider) {
Toast.makeText(context, "Provider: "+provider+" : Enabled", Toast.LENGTH_LONG).show();
}
public void onProviderDisabled(String provider) {
Toast.makeText(context, "Provider: "+provider+" : disabled", Toast.LENGTH_LONG).show();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Toast.makeText(context, "Provider: "+provider+" : status: "+status, Toast.LENGTH_LONG).show();
}
};
}
Also don't forget to add the permissions in AndroidManifest.xml
Do you really need a custom implementation for the location manager / location service's onLocationChanged() callback ?
Otherwise, you could take a look at OSMDroid's MyLocationNewOverlay class https://code.google.com/p/osmdroid/source/browse/trunk/osmdroid-android/src/main/java/org/osmdroid/views/overlay/mylocation/MyLocationNewOverlay.java?r=1220
There is also another implementation, (deprecated unfortunatelly) called MyLocationOverlay https://code.google.com/p/osmdroid/source/browse/trunk/osmdroid-android/src/org/osmdroid/views/overlay/MyLocationOverlay.java?r=902
In my implementation, I use it like this:
//declare variable; global - because I need reference elsewhere
private MyLocationOverlay self;
//somewhere in code
//'this' - is the context
//mapMainView - my mapView
self = new MyLocationOverlay(this, mapMainView);
self.enableMyLocation();
self.enableFollowLocation();
//add the overlay to the map and refresh the view
mapMainView.getOverlays().add(COUNT+1, self);//COUNT is the size of the List<Overlay> returned by mapMainView.getOverlays(); this is just because I want my 'self' to be always the last overlay added
mapMainView.invalidate();//refresh the view
This puts a default icon at my location on the map, and it updates constantly as I move.
I am new to android. i am trying to develop an app which fetch users current GPS coordinates and send them via sms to a hardcoded number. I am using two activities, first one has a progress bar and some text( Processing, Please wait),it is actually fetching GPS coordinates in background. The second one is receiving coordinates from first activity and sending the sms. The problem which i m facing is that in MainActivity.java file the condition if(latitude>0) is never satisfied since gps normally take some time to get coordinates and I cant go to second activity. I m attaching the code, please help me on this. you can edit the code if u like.
Thanks in Advance.
package com.shaji.smartcab;
import com.shaji.smartcab.MainActivity;
import com.shaji.smartcab.MyLocationListener;
import com.shaji.smartcab.R;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.TextView;
import android.widget.Toast;
import android.location.LocationListener;
import android.content.Context;
import android.content.Intent;
import android.location.LocationManager;
public class MainActivity extends Activiy{
double lat;
double lon;
String coordinates;
String coor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView tv= (TextView) findViewById(R.id.textView1);
LocationManager mlocManager=null;
LocationListener mlocListener;
mlocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
mlocListener = new MyLocationListener();
mlocManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 600,10, mlocListener);
if (mlocManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
if(MyLocationListener.latitude>0) {
lat = MyLocationListener.latitude;
lon = MyLocationListener.longitude;
tv.setText("m fetching coordinates");
coordinates= lat+","+lon;
Intent intent = new Intent(MainActivity.this, Sec.class);
intent.putExtra(coor, coordinates);
startActivity(intent);
//tv1.setText("Latitude:" + MyLocationListener.latitude + ",Longitude:" + MyLocationListener.longitude );
}}
else {
Context context = getApplicationContext();
CharSequence text = "Please turn ON GPS and Try again Later!";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
tv.setText(" ");
}
};
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}}
enter code herepackage com.shaji.smartcab;
import android.location.Location;
import android.location.LocationListener;
import android.os.Bundle;
public class MyLocationListener implements LocationListener {
public static double latitude;
public static double longitude;
#Override
public void onLocationChanged(Location loc)
{
loc.getLatitude();
loc.getLongitude();
latitude=loc.getLatitude();
longitude=loc.getLongitude();
}
#Override
public void onProviderDisabled(String provider)
{
//print "Currently GPS is Disabled";
}
#Override
public void onProviderEnabled(String provider)
{
//print "GPS got Enabled";
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras)
{
}
}
//this is the second activity.
package com.shaji.smartcab;
import com.shaji.smartcab.R;
import android.app.Activity;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class Sec extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.second);
final String sms = (String) getIntent().getExtras().get("coor");
Button c = (Button) findViewById(R.id.button1);
c.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
String phoneNo = "03136166588";
//String sms = "coordinates";
try {
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(phoneNo, null, sms, null, null);
Toast.makeText(getApplicationContext(), "Request Sent!",
Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(getApplicationContext(),
" Error, please try again later!",
Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}});
}}
I think the problem is, location update is not done before you call the next Activity.
Before you get the updates, get the co-ordinates using one of the 3 providers. Refer following code.
private Location getUserLocation() {
location_manager = (LocationManager) getSystemService(LOCATION_SERVICE);
if (location_manager != null) {
List<String > provider=location_manager .getAllProviders();
Location location = null;
for(int i=0;i<provider.size();i++){
location=location_manager .getLastKnownLocation(provider.get(i));
if(location!=null){
location_manager.requestLocationUpdates(provider.get(i),
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES,mlocListener);
break;
}
}
return location;
}
}
i have questions that i am really need some help on it:
i develop application and i want :
1-retrieve the user location and show it in the map.
2- the user can put pin in any place in the map and i should take the coordination to this pin and store it in variable
Note:my application in 2.1 should i use google API? if yes, does the google API support any activity rather than maps?
i search in google and find this code :
package com.java.locate;
import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class AndroidLbsGeocodingProjectActivity extends Activity {
/** Called when the activity is first created. */
private static final long MINIMUM_DISTANCE_CHANGE_FOR_UPDATES = 1; // in Meters
private static final long MINIMUM_TIME_BETWEEN_UPDATES = 1000; // in Milliseconds
protected LocationManager locationManager;
protected Button retrieveLocationButton;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
retrieveLocationButton = (Button) findViewById(R.id.retrieve_location_button);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MINIMUM_TIME_BETWEEN_UPDATES,
MINIMUM_DISTANCE_CHANGE_FOR_UPDATES,
new MyLocationListener()
);
retrieveLocationButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
showCurrentLocation();
}
});
}
protected void showCurrentLocation() {
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
String message = String.format(
"Current Location \n Longitude: %1$s \n Latitude: %2$s",
location.getLongitude(), location.getLatitude()
);
Toast.makeText(AndroidLbsGeocodingProjectActivity.this, message,
Toast.LENGTH_LONG).show();
}
}
private class MyLocationListener implements LocationListener {
public void onLocationChanged(Location location) {
String message = String.format(
"New Location \n Longitude: %1$s \n Latitude: %2$s",
location.getLongitude(), location.getLatitude()
);
Toast.makeText(AndroidLbsGeocodingProjectActivity.this, message, Toast.LENGTH_LONG).show();
}
public void onStatusChanged(String s, int i, Bundle b) {
Toast.makeText(AndroidLbsGeocodingProjectActivity.this, "Provider status changed",
Toast.LENGTH_LONG).show();
}
public void onProviderDisabled(String s) {
Toast.makeText(AndroidLbsGeocodingProjectActivity.this,
"Provider disabled by the user. GPS turned off",
Toast.LENGTH_LONG).show();
}
public void onProviderEnabled(String s) {
Toast.makeText(AndroidLbsGeocodingProjectActivity.this,
"Provider enabled by the user. GPS turned on",
Toast.LENGTH_LONG).show();
}
}
}
this is another code, this by using google API, but i have 2 issues in using this code :
1-it does not retrieve the user location, it is just show me the maps.
2-does google API working with another activity not just map?
package our.google.maps;
import java.util.List;
import java.util.Locale;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.MyLocationOverlay;
import com.google.android.maps.Overlay;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.os.Bundle;
import android.view.MotionEvent;
import android.widget.Toast;
public class MapsActivity extends MapActivity {
/** Called when the activity is first created. */
long start;
long stop;
MyLocationOverlay compass;
MapController controller;
MapView map;
//136
int x,y;
GeoPoint touchedPoint;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
map=(MapView) findViewById(R.id.mvMain);
map.setBuiltInZoomControls(true);
Touchy t = new Touchy();
List<Overlay> overlaylist= map.getOverlays();
overlaylist.add(t);
compass = new MyLocationOverlay (MapsActivity.this, map);
overlaylist.add(compass);
//map controller to go to Specific Location n36eeh el 6ol & el 3r'9 135
controller=map.getController();
GeoPoint point = new GeoPoint (51643234 , 7848593);
controller.animateTo(point);
controller.setZoom(6);
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
compass.disableCompass();
super.onPause();
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
compass.enableCompass();
super.onResume();
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
class Touchy extends Overlay {
public boolean onTouchEvent(MotionEvent e,MapView m){
if(e.getAction() == MotionEvent.ACTION_DOWN){
start = e.getEventTime();
x = (int) e.getX();
y = (int) e.getY();
touchedPoint = map.getProjection().fromPixels(x, y);
}
if (e.getAction() == MotionEvent.ACTION_UP) {
stop =e.getEventTime();
}
if(stop - start >1500) {
AlertDialog alert = new AlertDialog.Builder(MapsActivity.this).create();
alert.setTitle("Pick an option");
alert.setMessage(" i told u to pick an option");
alert.setButton("place a pin", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
} );
alert.setButton2("get an address", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
Geocoder geocode = new Geocoder (getBaseContext(),Locale.getDefault());
try {
}
finally{}}}
);
alert.setButton3("option3 ", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
} );
alert.show();
return true;
}
return false;
}
}
private class MyLocationListener implements LocationListener{
public void onLocationChanged1(Location location) {
String message = String.format(
"New Location \n Longitude: %1$s \n Latitude: %2$s",
location.getLongitude(), location.getLatitude()
);
Toast.makeText(MapsActivity.this, message, Toast.LENGTH_LONG).show();
}
public void onStatusChanged(String s, int i, Bundle b) {
Toast.makeText(MapsActivity.this, "Provider status changed",
Toast.LENGTH_LONG).show();
}
public void onProviderDisabled(String s) {
Toast.makeText(MapsActivity.this,
"Provider disabled by the user. GPS turned off",
Toast.LENGTH_LONG).show();
}
public void onProviderEnabled(String s) {
Toast.makeText(MapsActivity.this,
"Provider enabled by the user. GPS turned on",
Toast.LENGTH_LONG).show();
}
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
}
}
}
also,if my code is not correct, can you please give me the correct coed?
StackOverFlow members you are My HERO! help me PLEASE!
You can Use Google Maps.
You will require Map Api key.
If you are coding Using Eclipse then you can follow the procedure given on link
http://mobiforge.com/developing/story/using-google-maps-android