Localisation Service doesn't start android - java

I'm working on an android map and i'm trying to use Service class to find the current location of users. I had already succeed to do that whitout Service (directly in the main activity) but given the fact that i'll do network operations to find adresses and points of interest i thinked it was a good training to try Service with current location.
But the problem is my service doesn't start at all even if i reported it in the manifest
my class which extends Service :
`
package toutel.testcarte;
import org.osmdroid.bonuspack.overlays.Marker;
import org.osmdroid.util.GeoPoint;
import org.osmdroid.views.MapController;
import org.osmdroid.views.MapView;
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;
public class FindMe extends Service {
private MapView mapView;
private MapController mapController;
private LocationManager lm;
private 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(5 * 1000);
}
catch (InterruptedException e) {
e.printStackTrace();
}
mapView.getOverlays().clear();
}
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
}
};
public IBinder onBind(Intent arg0) {
return null;
}
public void onCreate(Bundle savedInstanceState) {
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 10000, 0,
mylocationlistener);
lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 10000, 0,
mylocationlistener);
super.onCreate();
}
public int onStartCommand(Intent intent, int flags, int startId) {
return super.onStartCommand(intent, flags, startId);
}
public void onDestroy() {
super.onDestroy();
lm.removeUpdates(mylocationlistener);
}
}
`
Im starting the service in the main activity with
startService(new Intent(MainActivity.this, FindMe.class));
and i added the service in the manifest :
<service android:name = "toutel.testcarte.FindMe"> </service>
So what am i doing wrong ?
Thanks !

Related

Jump to activity without button click

I am trying to go to next activity. After checking if the GPS is enabled
without any button click I am trying to jump to next activity.
But its not working
Is there any way to jump to nexy activity after checking if GPS is enabled
or after turning on GPS.
Help
Thanks.
Main.java
package app.example.joy;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.app.Activity;
import android.content.Intent;
public class Main extends Activity {
private LocationManager manager;
private LocationListener listner;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
manager = (LocationManager) getSystemService(LOCATION_SERVICE);
listner = new LocationListener() {
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String s) {
Intent i = new Intent(this, NextActivity.class);
startActivity(i);
}
#Override
public void onProviderDisabled(String s) {
// TODO Auto-generated method stub
Intent i = new Intent(
android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(i);
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
float latitude = (float) location.getLatitude();
float longitude = (float) location.getLongitude();
Intent i = new Intent(Main.this, NextActivity.class);
i.putExtra("Long", longitude);
i.putExtra("Lat", latitude);
startActivity(i);
}
};
}
}
I think the problem is that you've forgotten to even use the LocationManager that you instantiated. Try adding this line after instantiating the listener (at the end of your onCreate):
manager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, listener);
These will register for location updates using the named provider, and a pending intent.

Google Maps Android - tracking location changes

I'm developing a tracking application, for which I would also like be able to continue tracking when the application is sent to background. For this purpose I implemented a LocationListener. But clearly I'm missing something here, because during runtime none of the debug printlns appear, so the application never enters any of the inherited LocationListener functions.
michal.myapp.activities;
import java.util.ArrayList;
import java.util.Calendar;
import michal.myapp.R;
import michal.myapp.db.DataSource;
import michal.myapp.model.Track;
import android.content.Context;
import android.graphics.Color;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.PopupWindow;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
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.model.LatLng;
import com.google.android.gms.maps.model.PolylineOptions;
/**
* #author Michał Szydłowski
*
* Class representing user's map activity with location change detection and sensors.
*
*/
public class MapActivity extends FragmentActivity implements LocationListener,
SensorEventListener{
private GoogleMap map;
private DataSource dataSource;
private SensorManager sensorManager;
private Sensor senAccelerometer;
private ArrayList <LatLng> trackPoints;
private boolean zoomEnabled;
private Button saveTrackButton;
private static final long INTERVAL = 1000;
private static final float ACCURACY = 20;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
initialize();
check();
saveTrackButton = (Button) findViewById(R.id.saveTrackButton);
saveTrackButton.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
getDataFromPopupWindow();
}
});
}
private void check() {
if (GooglePlayServicesUtil.isGooglePlayServicesAvailable(this) != ConnectionResult.SUCCESS) {
System.out.println("yes");
}
String provider = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
Log.i("provider", "" + provider);
if (provider.equals("")) {
System.out.println("nope");
}
setUpMapIfNeeded();
}
private void initialize()
{
dataSource = new DataSource(this);
sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
senAccelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
sensorManager.registerListener(this, senAccelerometer , SensorManager.SENSOR_DELAY_NORMAL);
trackPoints = new ArrayList <LatLng> ();
zoomEnabled = true;
}
private void getDataFromPopupWindow()
{
LayoutInflater layoutInflater
= (LayoutInflater)getBaseContext()
.getSystemService(LAYOUT_INFLATER_SERVICE);
View popupView = layoutInflater.inflate(R.layout.save_track_window, null);
final PopupWindow popupWindow = new PopupWindow(
popupView,
LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT);
final EditText editName = (EditText) popupView.findViewById (R.id.trackName);
editName.requestFocus();
Button btnDismiss = (Button)popupView.findViewById(R.id.cancel);
btnDismiss.setOnClickListener(new Button.OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
popupWindow.dismiss();
}
});
Button btnSave = (Button) popupView.findViewById(R.id.save);
btnSave.setOnClickListener(new Button.OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String trackName = editName.getText().toString();
saveTrack(trackName);
popupWindow.dismiss();
}
});
popupWindow.setFocusable(true);
popupWindow.update();
popupWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
popupWindow.showAtLocation(saveTrackButton, Gravity.CENTER, 0, 0);
}
/**
* Saves the track to database when finished
*/
private void saveTrack(String trackName){
Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
String date = String.valueOf(year) + "-" + String.valueOf(month) + "-" + String.valueOf(day) ;
Track recordedTrack = new Track(trackName, trackPoints, date);
dataSource.open();
dataSource.insertTrack(recordedTrack);
dataSource.close();
}
/**
* Centers the view of the map around the current user's location.
* #param loc LatLng object representing user's current coordinates.
*/
private void zoom (LatLng loc)
{
if(zoomEnabled)
{
map.animateCamera(CameraUpdateFactory.newLatLngZoom(loc, 16));
zoomEnabled = false;
}
}
/** Initializes the GoogleMap object if it hasn't been already done.
* If successful, enables location tracking.
*/
private void setUpMapIfNeeded() {
// Do a null check to confirm that we have not already instantiated the map.
if (map == null) {
// Try to obtain the map from the SupportMapFragment.
map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map))
.getMap();
map.setMyLocationEnabled(true);
// Check if we were successful in obtaining the map.
if (map != null) {
//setUpMap();
setUpMap();
}
}
}
private void setUpMap()
{
LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, INTERVAL, ACCURACY, this);
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
System.out.println("setupmap");
}
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
dataSource.close();
super.onPause();
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
dataSource.open();
super.onResume();
setUpMapIfNeeded();
}
#Override
public void onAccuracyChanged(Sensor arg0, int arg1) {
// TODO Auto-generated method stub
}
#Override
public void onSensorChanged(SensorEvent event) {
Sensor mySensor = event.sensor;
if (mySensor.getType() == Sensor.TYPE_ACCELEROMETER) {
if(event.values[0] > 15 || event.values[1] > 15 || event.values[2] > 15)
{
// Intent intent = new Intent(this, CameraActivity.class);
// startActivity(intent);
}
}
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
LatLng loc = new LatLng(location.getLatitude(), location.getLongitude());
trackPoints.add(loc);
map.addPolyline(new PolylineOptions().addAll(trackPoints).width(5).color(Color.BLUE));
zoom (loc);
System.out.println("location changed");
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
System.out.println("status changed");
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
System.out.println("provider enabled");
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
System.out.println("provider disabled");
}
}
I have the following permissions in my Android Manifest:
<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="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCELEROMETER"/>
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
It is also worth mentioning, that I already try to attach an OnMyLocationChangeListener to my GoogleMap object, and it did track location changes, but not if the application was sent to background. Any ideas?

Android Google Maps v2 not showing Compass and Location Icon

I am not able to show the compass icon and the my location icon either. I have the code googleMap.getUiSettings.setMyLocationButtonEnabled(true) and googleMap.getUiSettings().setCompassEnabled(true); but it is not showing on the maps.
package com.ctc.weathermap;
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.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
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.provider.Settings;
import android.widget.Toast;
public class WeatherMapActivity extends Activity implements LocationListener {
private GoogleMap googleMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.weather_maps_main);
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);
LocationManager service = (LocationManager) getSystemService(LOCATION_SERVICE);
boolean enabledGPS = service.isProviderEnabled(LocationManager.GPS_PROVIDER);
boolean enabledWiFi = service.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!enabledGPS) {
Toast.makeText(this, "GPS signal not found", Toast.LENGTH_LONG).show();
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
else if(!enabledWiFi) {
Toast.makeText(this, "Network signal not found", Toast.LENGTH_LONG).show();
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
initializeMap();
googleMap.getUiSettings().setMyLocationButtonEnabled(true);
googleMap.getUiSettings().setCompassEnabled(true);
}
private void initializeMap() {
// check if map is created
if(googleMap == null) {
googleMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap(); // creates the map
// check if map is created successfully or not
if (googleMap == null) {
Toast.makeText(getApplicationContext(),
"Map could not be created", Toast.LENGTH_SHORT)
.show();
}
}
}
#Override
protected void onResume() {
super.onResume();
initializeMap();
}
#Override
public void onLocationChanged(Location location) {
googleMap.clear();
MarkerOptions marker = new MarkerOptions().position(new LatLng(location.getLatitude(), location.getLongitude()));
marker.title("Current location");
marker.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_CYAN));
googleMap.addMarker(marker);
googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(location.getLatitude(), location.getLongitude()), 16));
}
#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
}
}
The rest of the code works such as markers and what not. I have tried putting the code for location and compass in initializeMap() but it still does not show up. I would appreciate any help. Thank you!
You havent enabled the my-location layer.Check this link for more details
So please do
googleMap.setMyLocationEnabled(true);
before
googleMap.getUiSettings().setMyLocationButtonEnabled(true);
googleMap.getUiSettings().setCompassEnabled(true);
This will make your setMyLocationButton come up..
And,the compass icon will appear only if you rotate the map to not align to north.

The constructor GPS(MainActivity) is undefined

I am getting this error The constructor GPS(MainActivity) is undefined after building a class to handle LocationManager interface (GPS).
... I am totally blank, I do not know what to say. I do not have much experience with java, class and interface.
The codes are posted below.
MainActivity.java
package com.bz.example;
import android.app.Activity;
import android.os.Bundle;
import com.bz.example.libs.GPS;
import com.bz.example.libs.GPSpos;
public class MainActivity extends Activity implements GPSpos {
private GPS gps;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
gps = new GPS(MainActivity.this);
}
public void locationChanged(double longitude, double latitude) {
}
#Override
public void displayGPSSettingsDialog() {
}
}
GPSpos.java
package com.bz.example.libs;
public interface GPSpos {
public void locationChanged(double longitude, double latitude);
public void displayGPSSettingsDialog();
}
GPS.java
package com.bz.example.libs;
import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
public class GPS {
private GPSpos main;
// Helper for GPS-Position
private LocationListener locationListener;
private LocationManager locationManager;
private boolean isRunning;
public void GPS(GPSpos main)
{
this.main = main;
locationManager = (LocationManager) ((Activity) this.main).getSystemService(Context.LOCATION_SERVICE);
locationListener = new locationListener();
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 3000, 10, locationListener);
}
public void stopGPS() {
if(isRunning) {
locationManager.removeUpdates(locationListener);
this.isRunning = false;
}
}
public void resumeGPS() {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 3000, 10, locationListener);
this.isRunning = true;
}
public boolean isRunning() {
return this.isRunning;
}
public class locationListener implements LocationListener {
#Override
public void onLocationChanged(Location loc) {
GPS.this.main.locationChanged(loc.getLongitude(), loc.getLatitude());
}
#Override
public void onProviderDisabled(String provider) {
GPS.this.main.displayGPSSettingsDialog();
}
#Override
public void onProviderEnabled(String provider) {}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {}
}
}
remove void:
public void GPS(GPSpos main)
^^^^ - constructors in java dont have return type

Android GPS app not working

i have tryed to make my own app and to use google maps. I want it to set the center of the map on my curent gps position, but when i have a gps lock on my phone i will just go to these coordinates (0,0) I dont know where i went wrong. Thanks everybody :D
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
public class Courses extends MapActivity {
MapView map;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.courses);
MapView map = (MapView) findViewById (R.id.MapView);
map.setBuiltInZoomControls(true);
map.setSatellite(true);
final MapController control = map.getController();
LocationManager manager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
LocationListener listener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
control.setCenter(new GeoPoint((int)location.getLatitude(),(int)location.getLongitude()));
control.setZoom(19);
}
#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
}
};
manager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, listener);
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
}
`
The first issue I see here is, that location.getLatitude() and location.getLongitude() return float, which have to be multiplied with 1E6 and then casted as an int to be acceptible for GeoPoint. This also explains why you have coordinates of approximately 0,0
I would suggest replacing your control.setCenter(new GeoPoint((int)location.getLatitude(),(int)location.getLongitude())); with control.setCenter(new GeoPoint((int)(location.getLatitude() * 1E6),(int)(location.getLongitude() * 1E6)));
Try that, it should work then.

Categories