Osmdroid Overlays crash application (Android) - android

package gpstest.example.com;
import org.osmdroid.tileprovider.tilesource.TileSourceFactory;
import org.osmdroid.views.overlay.MyLocationOverlay;
import org.osmdroid.util.GeoPoint;
import org.osmdroid.views.MapView;
import android.content.Context;
import android.graphics.Paint;
import android.app.Activity;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Toast;
public class gpstestActivity extends Activity
{
public LocationManager mlocManager;
public LocationListener mlocListener;
public boolean isFirstRun=true;
protected final Paint mPaint = new Paint();
private MapView myMap;
private MyLocationOverlay myLocOverlay;
/** Called when the activity is first created. */
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
gpsEnable();
setMap();
initMyLocation();
}
public void setMap(){
MapView map = (MapView) findViewById(R.id.map);
map.setTileSource(TileSourceFactory.MAPNIK);
map.setBuiltInZoomControls(true);
map.setMultiTouchControls(true);
map.getController().setZoom(16);
map.getController().setCenter(new GeoPoint(30266000, -97739000));
}
private void initMyLocation() {
myLocOverlay = new MyLocationOverlay(this, myMap);
myLocOverlay.enableMyLocation();
myMap.getOverlays().add(myLocOverlay);
}
public void gpsEnable (){
mlocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
mlocListener = new MyLocationListener();
mlocManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 10, 50, mlocListener);
}
public void gpsDisable(){
mlocManager.removeUpdates(mlocListener);}
/* Class My Location Listener */
public class MyLocationListener implements LocationListener
{
#Override
public void onLocationChanged(Location loc)
{
loc.getLatitude();
loc.getLongitude();
double longi=loc.getLongitude();
double lati=loc.getLatitude();
MapView map = (MapView) findViewById(R.id.map);
map.getController().setCenter(new GeoPoint(lati, longi));
String Text="My current location is: " +
"Latitud = " + loc.getLatitude() +
"Longitud = " + loc.getLongitude();
Toast.makeText( getApplicationContext(),
Text,
Toast.LENGTH_SHORT).show();
//initMyLocation();
}
#Override
public void onProviderDisabled(String provider)
{
Toast.makeText( getApplicationContext(),
"Gps Disabled",
Toast.LENGTH_SHORT ).show();
mlocManager.removeUpdates(mlocListener);
}
#Override
public void onProviderEnabled(String provider)
{
Toast.makeText( getApplicationContext(),
"Gps Enabled",
Toast.LENGTH_SHORT).show();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras)
{
Toast.makeText( getApplicationContext(),
"Status changed",
Toast.LENGTH_SHORT).show();
}
}/* End of Class MyLocationListener */
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.beenden: mlocManager.removeUpdates(mlocListener);}
return true;
}
protected void onPause(){
Toast.makeText( getApplicationContext(),
"On Pause",
Toast.LENGTH_SHORT).show();
gpsDisable();
isFirstRun=false;
super.onPause();
}
protected void onDestroy(){
Toast.makeText( getApplicationContext(),
"Destroyed",
Toast.LENGTH_SHORT).show();
gpsDisable();
super.onDestroy();
}
protected void onResume(){
if (isFirstRun==false){gpsEnable();}
Toast.makeText( getApplicationContext(),
"Resumed",
Toast.LENGTH_SHORT).show();
super.onResume();
}
}/* Ende Activity */
Whenever I call initMyLocation, the app crashes (bot on emulator and device). Same happens when I try to implement a MiniMap. I do exactly the same as in the SampleExtensive example from the Osmdroid repository. What am I doing wrong?
My AndroidManifest.xml is giving all required permissions I think
<?xml version="1.0" encoding="utf-8"?>
<application android:icon="#drawable/icon" android:label="#string/app_name">
<activity android:name=".gpstestActivity"
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>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission>
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

In your setMap(), you never set
myMap = map;
So in initMyLocation, you are passing null for the pMapView parameter.

to use location you must have the following in your AndroidManifest.xml :
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission>

Related

Showing Error ---java.lang.NoClassDefFoundError

When I press the button btnlocation it should go to the Mapsactivity
but it is giving me the error:
java.lang.NoClassDefFoundError
I also added MapsActivity in manifest as usual .. .but why this error? I need the solution.Can any one help me please...
package com.mamun.tasktest;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.Fragment;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.LocationManager;
import android.os.Bundle;
import android.provider.Settings;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
public class FragmentB extends Fragment implements OnClickListener {
private Button btnLocation;
private LocationManager manager;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.frag_b, null, false);
btnLocation = (Button) view.findViewById(R.id.btnLocation);
btnLocation.setOnClickListener(this);
manager = (LocationManager)getActivity().getSystemService(Context.LOCATION_SERVICE);
if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("GPS is currently disabled");
builder.setMessage("Please enable GPS for better view of your location.\nWould you like to change these settings now?");
builder.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent i = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(i);
}
});
builder.setNegativeButton("No",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
getActivity();
}
});
builder.create().show();
}
return view;
}
#Override
public void onClick(View v) {
if(isMapAvailalble()){
/////////////////////////////
/*
// */
//////////////////////////
Intent in = new Intent(getActivity(),MapsActivity.class);
startActivity(in);
}
}
/*Intent intent = new Intent("android.location.GPS_ENABLED_CHANGE"); intent.putExtra("enabled", false);
sendBroadcast(intent);*/
//if googleplayservis or play store is not available/updated or user recoverable problem occured.
public boolean isMapAvailalble()
{
// to test if there is no googleplayservise
//int resultcode=ConnectionResult.SERVICE_MISSING;
int resultcode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getActivity());
if(ConnectionResult.SUCCESS==resultcode)
{
return true;
}
else if(GooglePlayServicesUtil.isUserRecoverableError(resultcode))
{
Dialog d = GooglePlayServicesUtil.getErrorDialog(resultcode, getActivity(), 1);
d.show();
}
else
{
Toast.makeText(getActivity()," Google Map API is not supported in your device",Toast.LENGTH_LONG).show();
}
return false;
}
/*public void turnGPSOn()
{
Intent intent = new Intent("android.location.GPS_ENABLED_CHANGE");
intent.putExtra("enabled", true);
((Context) this.ctx).sendBroadcast(intent);
#SuppressWarnings("deprecation")
String provider = Settings.Secure.getString(((Context) ctx).getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
if(!provider.contains("gps")){ //if gps is disabled
final Intent poke = new Intent();
poke.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider");
poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
poke.setData(Uri.parse("3"));
((Context) this.ctx).sendBroadcast(poke);
}*/
}
Manifest.xml file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.mamun.tasktest"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="11"
android:targetSdkVersion="16" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<uses-permission android:name="com.mamun.tasktest.permission.MAPS_RECEIVE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-library android:name="com.google.android.maps"/>
<permission
android:name="com.mamun.tasktest.permission.MAPS_RECEIVE"
android:protectionLevel="signature" >
</permission>
<uses-feature
android:glEsVersion="0x00020000"
android:required="true" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.mamun.tasktest.MainActivity"
android:label="#string/app_name"
android:screenOrientation="portrait" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="AIzaSyCgGng3iaqbTxJ3B_lYemZBEqXOonUtFEI" />
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
<activity android:name="MapsActivity"></activity>
</application>
</manifest>
MapsActivity
package com.mamun.tasktest;
import java.io.IOException;
import java.util.ArrayList;
import android.app.Activity;
import android.graphics.Canvas;
import android.graphics.Point;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesClient;
import com.google.android.gms.location.LocationClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.MapView;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.maps.MapActivity;
public class MapsActivity<GeoPoint, OverlayItem> extends MapActivity implements
GooglePlayServicesClient.ConnectionCallbacks,
GooglePlayServicesClient.OnConnectionFailedListener, LocationListener {
MapView mapView;
com.google.android.maps.GeoPoint p;
private LocationManager manager;
private TextView tvAddress;
private Button btnSearch;
private EditText etSearch;
private LocationClient locationClient;
private GoogleMap googleMap;
private MapFragment mapFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.map);
manager = (LocationManager) getSystemService(LOCATION_SERVICE);
tvAddress = (TextView) findViewById(R.id.tvaddress);
btnSearch = (Button) findViewById(R.id.btnSearch);
etSearch = (EditText) findViewById(R.id.etSearch);
mapFragment = (MapFragment) getFragmentManager().findFragmentById(
R.id.maps);
googleMap = mapFragment.getMap();
locationClient = new LocationClient(this, this, this);
}
public void onSearch(View v) {
// Getting user input location
String location = etSearch.getText().toString();
if (location != null && !location.equals("")) {
new GeocoderTask().execute(location);
}
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
locationClient.connect();
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
locationClient.disconnect();
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
}
#Override
public void onConnectionFailed(ConnectionResult result) {
}
#Override
public void onConnected(Bundle connectionHint) {
try {
Location currentLocation = locationClient.getLastLocation();
double lat = currentLocation.getLatitude();
double lng = currentLocation.getLongitude();
// txtLocation.setText(lat + ", " + lng);
Geocoder geocoder = new Geocoder(this);
ArrayList<Address> address = (ArrayList<Address>) geocoder
.getFromLocation(currentLocation.getLatitude(),
currentLocation.getLongitude(), 5);
Address addr = address.get(0);
String currentAddress = (addr.getAddressLine(0) + "-"
+ addr.getAdminArea() + "-" + addr.getLocality() + "-"
+ addr.getPostalCode() + "-" + addr.getCountryCode());
MarkerOptions options = new MarkerOptions();
options.position(new LatLng(lat, lng));
options.title(currentAddress);
options.snippet("Current location");
options.icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_AZURE));
if (googleMap != null) {
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(
new LatLng(lat, lng), 14.0f));
googleMap.addMarker(options);
} else {
Toast.makeText(getApplicationContext(), "Map is null",
Toast.LENGTH_LONG).show();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public void onDisconnected() {
// TODO Auto-generated method stub
}
// An AsyncTask class for accessing the GeoCoding Web Service
private class GeocoderTask extends
AsyncTask<String, Void, ArrayList<Address>> {
#Override
protected ArrayList<Address> doInBackground(String... locationName) {
// Creating an instance of Geocoder class
Geocoder geocoder = new Geocoder(getBaseContext());
ArrayList<Address> addresses = null;
try {
// Getting a maximum of 3 Address that matches the input text
addresses = (ArrayList<Address>) geocoder.getFromLocationName(
locationName[0], 3);
} catch (IOException e) {
e.printStackTrace();
}
return addresses;
}
#Override
protected void onPostExecute(ArrayList<Address> addresses) {
if (addresses == null || addresses.size() == 0) {
Toast.makeText(getBaseContext(), "No Location found",
Toast.LENGTH_SHORT).show();
return;
}
// Clears all the existing markers on the map
googleMap.clear();
// Adding Markers on Google Map for each matching address
for (int i = 0; i < addresses.size(); i++) {
Address address = (Address) addresses.get(i);
// Creating an instance of GeoPoint, to display in Google Map
LatLng latLng;
latLng = new LatLng(address.getLatitude(),
address.getLongitude());
String addressText = String.format(
"%s, %s",
address.getMaxAddressLineIndex() > 0 ? address
.getAddressLine(0) : "", address
.getCountryName());
MarkerOptions markerOptions = new MarkerOptions();
// markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title(addressText);
googleMap.addMarker(markerOptions);
// Locate the first location
if (i == 0)
googleMap.animateCamera(CameraUpdateFactory
.newLatLng(latLng));
}
}
}
class MapOverlay extends com.google.android.maps.Overlay {
#Override
public void draw(Canvas canvas, com.google.android.maps.MapView mapView,
boolean shadow) {
// TODO Auto-generated method stub
super.draw(canvas, mapView, shadow);
Point screenPts = new Point();
mapView.getProjection().toPixels(p, screenPts);
}
#Override
public boolean onTouchEvent(MotionEvent e,
com.google.android.maps.MapView mapView) {
// TODO Auto-generated method stub
if (e.getAction() == 1) {
com.google.android.maps.GeoPoint p = mapView.getProjection().fromPixels(
(int) e.getX(), (int) e.getY());
Toast.makeText(
getBaseContext(),
"Lat: " + p.getLatitudeE6() / 1E6 + ", Lon: "
+ p.getLongitudeE6() / 1E6, Toast.LENGTH_SHORT)
.show();
}
return false;
}
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
}
Add Activity into your manifest.xml because you need to give all path if your Activity located into different package.
<activity
android:name="com.mamun.tasktest.MapsActivity"
android:label="MapActivity" >
</activity>
And/or is your Activity belong to the same package then add simply
<activity android:name=".MapsActivity"></activity>
For more information go to:http://developer.android.com/guide/topics/manifest/manifest-intro.html
This is incorrect:
<activity android:name="MapsActivity"></activity>
You need to give full or relative path like this:
<activity android:name="com.mamun.tasktest.MapsActivity"></activity>
or
<activity android:name=".MapsActivity"></activity>
Replace your this tag in manifest
<activity android:name="MapsActivity"></activity>
by :
<activity android:name=".MapsActivity"></activity>
you should specify your full package name while declaring your activity into manifets.
See this link for reference:-
Add a new activity to the AndroidManifest?
You just forget to place a DOt (.) before MapsActivity. So, without that Dot (.) your class path looks like...
com.mamun.tasktestMapsActivity.java
But, it should be as....
com.mamun.tasktest.MapsActivity.java
Now, change this line of your Manifest...
<activity android:name="MapsActivity"></activity>
to...
<activity android:name=".MapsActivity"></activity>
I got the solution....The line "" should be inside application not inside directly on manifest.Like as below....

Get Location From Offline Application

I'd like to get Geo location by using GPS provider. So my code will be like this
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.provider.Settings;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
LocationManager lm;
TextView textLatitude, textLongitude;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textLatitude = (TextView)findViewById(R.id.textLatitude);
textLongitude = (TextView)findViewById(R.id.textLongitude);
lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
/* Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);*/
}
public void onResume() {
super.onResume();
setup();
}
public void onStart() {
super.onStart();
boolean gpsEnabled, networkEnabled;
gpsEnabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
Log.d("LocationService","GPS Status: "+gpsEnabled);
if(!gpsEnabled) {
networkEnabled =
lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if(!networkEnabled) {
Intent intent =
new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
}
}
public void onStop() {
super.onStop();
lm.removeUpdates(listener);
}
public void setup() {
lm.removeUpdates(listener);
String latitude = "Unknown";
String longitude = "Unknown";
Location gpsLocation = requestUpdatesFromProvider(
LocationManager.GPS_PROVIDER, "GPS not supported");
if(gpsLocation != null) {
Log.d("Location Service","GET FROM GPS");
latitude = String.format("%.7f", gpsLocation.getLatitude());
longitude = String.format("%.7f", gpsLocation.getLongitude());
}
textLatitude.setText(latitude);
textLongitude.setText(longitude);
}
public Location requestUpdatesFromProvider(final String provider
, String error) {
Location location = null;
if (lm.isProviderEnabled(provider)) {
lm.requestLocationUpdates(provider, 0, 0, listener);
Log.d("LocationService","Requesting...");
location = lm.getLastKnownLocation(provider);
//Log.d("LocationSerivce", "Geo :"+location.getLatitude());
} else {
Toast.makeText(this, error, Toast.LENGTH_LONG).show();
}
return location;
}
public LocationListener listener = new LocationListener() {
public void onLocationChanged(Location location) {
textLatitude.setText(String.format("%.7f", location.getLatitude()));
textLongitude.setText(String.format("%.7f",location.getLongitude()));
}
public void onProviderDisabled(String provider) { }
public void onProviderEnabled(String provider) { }
public void onStatusChanged(String provider
, int status, Bundle extras) { }
};
}
The result is ... IT DOESN'T WORK. What have I done wrong?
I've also added permission to manifest file already.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.locationservice"
android:versionCode="1"
android:versionName="1.0" >
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name
="com.google.android.providers.gsf.permission.READ_GSERVICES"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.locationservice.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>
</application>
</manifest>
I search a lot from Internet and I got that it'll work if I combine with Network provider and I have to use internet to get my location. This is not what I want.
I want to get Location from GPS only because I'll use for offline application.
Could you give me any great suggestion. I'll thanks a lot

LocationManager requestLocationUpdates not working

I Have This Creepy problem. i am trying to get the location of my emulator. it working fine when i get the location of my emulator. but when i change my location coordinates nothing happens. gps is working fine.
Here is my code
Main.java
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.widget.TextView;
public class Main extends Activity {
TextView tvStatus;
LocationManager lm;
boolean gpsEnabled;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvStatus = (TextView) findViewById(R.id.textView1);
lm = (LocationManager) getSystemService(LOCATION_SERVICE);
if (lm.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
Log.d("", "GPS is Active");
Location l = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
tvStatus.setText(l.getLatitude()+" , "+l.getLongitude());
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0,
new LocationListener() {
#Override
public void onStatusChanged(String arg0, int arg1,
Bundle arg2) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onProviderDisabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onLocationChanged(Location arg0) {
tvStatus.setText("GPS ENABLED: " + gpsEnabled
+ "\nLatitude: " + arg0.getLatitude()
+ "\nLongitude: " + arg0.getLongitude());
}
});
}
}
}
Manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.enabelinglocationprovider"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="5"
android:targetSdkVersion="10" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.enabelinglocationprovider.Main"
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>
Samsung phones have this problem. There is hack to this. You need to kick the locationmanager on the butt to get the latest location from the maps cache.
God.locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0,
new LocationListener() {
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onLocationChanged(final Location location) {
}
});
currentLocation = God.locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
Call getLastKnownLocation after kicking the requestLocationUpdates with 0's.
It happens with emulators, try rebooting the emulator.
Or, close both eclipse and emulator and start both again

gps monitoring service in android

I'm trying to create a program for android that constantly (every minute) gets the gps location and then sends it to my server at home (so that i always know where my phone is).
I created a gui with a start-button which starts the service:
start.setOnClickListener(new View.OnClickListener() {
synchronized public void onClick(View v) {
startService(new Intent(GpsTest2.this, GTService.class));
}
});
Then my service is declared like this:
public class GTService extends Service implements LocationListener {
}
This GTService has a method for retrieving the data:
public void onLocationChanged(Location location) {
}
#Override
public void onCreate() {
super.onCreate();
LocationManager locMgr = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locMgr.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, interval * 1000, minDist, this);
}
In AndroidManifest.xml I have:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<service android:name=".GTService">
</service>
This doesn't seem to work: no data is logged.
What am I doing wrong here?
Your code seems to be working fine except this,
You are using LocationManager.NETWORK_PROVIDER
locMgr.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, interval * 1000, minDist, this);
Where as it should be LocationManager.GPS_PROVIDER
locMgr.requestLocationUpdates(LocationManager.GPS_PROVIDER, 2 * 1000, 10, locationListener);
Hope this will surely do for you. Thanks.
The location from Network provider is not accurate. PLease use GPS instead. If you really want to user Network only then I would recomond to set minDistance param as 0
The following should work fine,
Manifest :
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.smartconcept.locationmonitor.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:name=".GTService" />
</application>
GTService :
import android.app.Service;
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.os.IBinder;
import android.widget.Toast;
public class GTService extends Service implements LocationListener {
LocationManager locMgr;
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate(){
super.onCreate();
locMgr = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locMgr.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1 * 1000, 0, this);
}
#Override
public void onDestroy(){
super.onDestroy();
locMgr.removeUpdates(this);
}
#Override
public void onLocationChanged(Location loc) {
Toast.makeText(getBaseContext(), String.valueOf(loc.getLatitude()) + "\n" + String.valueOf(loc.getLongitude()), Toast.LENGTH_SHORT).show();
}
#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
}
}
MainActivity:
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnStart = (Button)findViewById(R.id.btnStart);
btnStart.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
startService(new Intent(MainActivity.this,GTService.class));
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
Hope this helps.

Auto Sends GPS Coordinates via SMS

I made an Application that shows my GPS coordinates (Langitude and Latitude) number, which designed with out a map. But I would like to send the lat and long to mobile number/phone number Automatically (no need a send button) every time I open this Application. Anyone can help me..
Gps.java
package Sample.gps.send;
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.widget.Toast;
public class Gps extends Activity
{
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
/* Use the LocationManager class to obtain GPS locations */
LocationManager mlocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
LocationListener mlocListener = new MyLocationListener();
mlocManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 0, 0, mlocListener);
}
/* Class My Location Listener */
public class MyLocationListener implements LocationListener
{
#Override
public void onLocationChanged(Location loc)
{
loc.getLatitude();
loc.getLongitude();
String Text = "My location is: " +
"Latitude = " + loc.getLatitude() +
"Longitude = " + loc.getLongitude();
Toast.makeText( getApplicationContext(),Text,Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderDisabled(String provider)
{
Toast.makeText( getApplicationContext(),
"GPS Disabled",
Toast.LENGTH_SHORT ).show();
}
#Override
public void onProviderEnabled(String provider)
{
Toast.makeText( getApplicationContext(),
"GPS Enabled",
Toast.LENGTH_SHORT).show();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras)
{
}
}
}
Here is for the AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="Sample.gps.send"
android:versionCode="1"
android:versionName="1.0">
<application android:icon="#drawable/icon"
android:label="#string/app_name">
<activity android:name=".UseGps"
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>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION">
</uses-permission>
<uses-permission android:name="android.permission.SEND_SMS">
</uses-permission>
</manifest>
Here MyLocationListener is an inner class. Can anyone tell how to retrieve the coordinates whenever onLocationChanged method is called? The location is displayed using a Toast. Is it possible to get the coordinates by calling any method from onCreate()?
See, http://mobiforge.com/developing/story/sms-messaging-android. That tutorial will show you how to send an SMS, using that you should be able to figure out what you need to do.
Please use the code tags when posting code samples :-)

Categories

Resources