Error at #Override in Google Maps API V2 Sample Code - android

I want to run the sample codes for Google Maps API V2. I followed these steps, but a problem occurs. I have got a compiler error in the most Activities.
Error: The method activate(LocationSource.OnLocationChangedListener)
of type LocationSourceDemoActivity.LongPressLocationSource must
override a superclass method
In the following code these methods got an error:
public void activate(OnLocationChangedListener listener)
public void deactivate()
public void onMapLongClick(LatLng point)
Code:
package com.example.mapdemo;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnMapLongClickListener;
import com.google.android.gms.maps.LocationSource;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import android.app.Activity;
import android.location.Location;
import android.os.Bundle;
/**
* This shows how to use a custom location source.
*/
public class LocationSourceDemoActivity extends android.support.v4.app.FragmentActivity {
/**
* A {#link LocationSource} which reports a new location whenever a user long presses the map at
* the point at which a user long pressed the map.
*/
private static class LongPressLocationSource implements LocationSource, OnMapLongClickListener {
private OnLocationChangedListener mListener;
/**
* Flag to keep track of the activity's lifecycle. This is not strictly necessary in this
* case because onMapLongPress events don't occur while the activity containing the map is
* paused but is included to demonstrate best practices (e.g., if a background service were
* to be used).
*/
private boolean mPaused;
#Override
public void activate(OnLocationChangedListener listener) {
mListener = listener;
}
#Override
public void deactivate() {
mListener = null;
}
#Override
public void onMapLongClick(LatLng point) {
if (mListener != null && !mPaused) {
Location location = new Location("LongPressLocationProvider");
location.setLatitude(point.latitude);
location.setLongitude(point.longitude);
location.setAccuracy(100);
mListener.onLocationChanged(location);
}
}
public void onPause() {
mPaused = true;
}
public void onResume() {
mPaused = false;
}
}
private LongPressLocationSource mLocationSource;
private GoogleMap mMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.basic_demo);
mLocationSource = new LongPressLocationSource();
setUpMapIfNeeded();
}
#Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
mLocationSource.onResume();
}
private void setUpMapIfNeeded() {
// Do a null check to confirm that we have not already instantiated the map.
if (mMap == null) {
// Try to obtain the map from the SupportMapFragment.
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
// Check if we were successful in obtaining the map.
if (mMap != null) {
setUpMap();
}
}
}
private void setUpMap() {
mMap.setLocationSource(mLocationSource);
mMap.setOnMapLongClickListener(mLocationSource);
mMap.setMyLocationEnabled(true);
}
#Override
protected void onPause() {
super.onPause();
mLocationSource.onPause();
}
}
I attached the library and I haven't skipped a step from Google's guide.
I hope somebody of you can help me!

Do you use a java 1.6 compliant compiler? The usage of the #Override annotation is different in 1.5 and 1.6 (see this answer).
Right-click on your project node, choose "Properties"-->"Java Compiler"-->"Compiler compliance level" should be 1.6.

Related

Routing between two points in Mapbox (Android)

I am using MapBox to create a route between two points. I have LatLng of two points already and have successfully add Markers at source and destination point but the problem is, I am unable to create a route between them. Here is the code. I don't know where i am lacking but i have followed a tutorial but in that Tutor is creating a route between current location and the location clicked on map and he is doing stuff in onMapClicked method since i am not using that approach due to have customized point. Instead, i am doing stuff in the onMapReady method other than all the procedure is identical.
package com.devaj.googlemaps;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import com.devaj.googlemaps.models.TDD;
import com.mapbox.api.directions.v5.models.DirectionsResponse;
import com.mapbox.api.directions.v5.models.DirectionsRoute;
import com.mapbox.geojson.Point;
import com.mapbox.mapboxsdk.Mapbox;
import com.mapbox.mapboxsdk.annotations.MarkerOptions;
import com.mapbox.mapboxsdk.geometry.LatLng;
import com.mapbox.mapboxsdk.maps.MapView;
import com.mapbox.mapboxsdk.maps.MapboxMap;
import com.mapbox.mapboxsdk.maps.OnMapReadyCallback;
import com.mapbox.mapboxsdk.maps.Style;
import com.mapbox.services.android.navigation.ui.v5.route.NavigationMapRoute;
import com.mapbox.services.android.navigation.v5.navigation.NavigationRoute;
public class NavigationActivity extends AppCompatActivity implements OnMapReadyCallback{
public static final String TAG = "NavigationActivity";
private MapView mapView;
private TDD tdd;
private Point originPosition, dstPosition;
private Double originLat, originLng, dstLat, dstLng;
private LatLng originLatLng, dstLatLng;
private MapboxMap map;
private NavigationMapRoute navigationMapRoute;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Mapbox.getInstance(this, getString(R.string.access_token));
setContentView(R.layout.activity_navigation);
MapBox(savedInstanceState);
}
#Override
public void onMapReady(#NonNull MapboxMap mapboxMap) {
map = mapboxMap;
originPosition = Point.fromLngLat(originLat, originLng);
dstPosition = Point.fromLngLat(dstLat, dstLng);
MarkerOptions options = new MarkerOptions();
options.title("Source");
options.position(originLatLng);
MarkerOptions options1 = new MarkerOptions();
options1.title("Destination");
options1.position(dstLatLng);
mapboxMap.addMarker(options);
mapboxMap.addMarker(options1);
mapboxMap.setStyle(Style.MAPBOX_STREETS, new Style.OnStyleLoaded() {
#Override
public void onStyleLoaded(#NonNull Style style) {
navigationMapRoute = new NavigationMapRoute(null, mapView, map, R.style.NavigationMapRoute);
getRoute(originPosition, dstPosition);
}
});
}
private void MapBox(Bundle savedInstanceState)
{
Intent i = getIntent();
tdd = (TDD) i.getSerializableExtra("tdd");
originLat = Double.parseDouble(tdd.getmSrcLat());
originLng = Double.parseDouble(tdd.getmSrcLng());
dstLat = Double.parseDouble(tdd.getmDstLat());
dstLng = Double.parseDouble(tdd.getmDstLng());
originLatLng = new LatLng(originLat, originLng);
dstLatLng = new LatLng(dstLat, dstLng);
mapView = findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(this);
}
private void getRoute(Point origin, Point destination)
{
// CameraPosition position = new CameraPosition.Builder()
// .target(originLatLng) // Sets the new camera position
// .zoom(17) // Sets the zoom
// .bearing(180) // Rotate the camera
// .tilt(30) // Set the camera tilt
// .build(); // Creates a CameraPosition from the builder
//
// map.animateCamera(CameraUpdateFactory
// .newCameraPosition(position), 7000);
NavigationRoute.builder(NavigationActivity.this)
.accessToken(Mapbox.getAccessToken())
.origin(origin)
.destination(destination)
.build()
.getRoute(new Callback<DirectionsResponse>() {
#Override
public void onResponse(Call<DirectionsResponse> call, Response<DirectionsResponse> response) {
if (response.body() == null)
{
Usable.logMessage(TAG, "No routes found, Check User and Access Token..");
return;
} else if (response.body().routes().size() == 0)
{
Usable.logMessage(TAG, "No routes found..");
return;
}
DirectionsRoute currentRoute = response.body().routes().get(0);
navigationMapRoute.addRoute(currentRoute);
}
#Override
public void onFailure(Call<DirectionsResponse> call, Throwable t) {
Log.e(TAG, "Error: "+ t.getMessage());
}
});
}
#Override
protected void onStart() {
super.onStart();
mapView.onStart();
}
#Override
protected void onResume() {
super.onResume();
mapView.onResume();
}
#Override
protected void onPause() {
super.onPause();
mapView.onPause();
}
#Override
protected void onStop() {
super.onStop();
mapView.onStop();
}
#Override
protected void onSaveInstanceState(#NonNull Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
#Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
#Override
protected void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
}
You've got your lat/long order mixed up whenever you use Point.fromLngLat().
For example, dstPosition = Point.fromLngLat(dstLat, dstLng); is the wrong order.
Is there a log message in your logcat when you try the code you posted above? Search for Mbgl. Is response.body() null? Is the route size == 0? Basically, it'd be helpful if you could explain more when you say I am unable to create a route between them.
By the way, you don't have to use the Mapbox Navigation SDK for Android if you want to get a route between two points. The Mapbox Java SDK can do that.
https://docs.mapbox.com/android/java/overview/directions
https://docs.mapbox.com/android/java/examples/show-directions-on-a-map
https://docs.mapbox.com/android/java/examples/dashed-directions-line
Also, I'd move the onMapReady() stuff into the onStyleLoaded() callback.
#Override
public void onMapReady(#NonNull MapboxMap mapboxMap) {
mapboxMap.setStyle(Style.MAPBOX_STREETS, new Style.OnStyleLoaded() {
#Override
public void onStyleLoaded(#NonNull Style style) {
map = mapboxMap;
originPosition = Point.fromLngLat(originLng, originLat);
dstPosition = Point.fromLngLat(dstLng, dstLat);
MarkerOptions options = new MarkerOptions();
options.title("Source");
options.position(originLatLng);
MarkerOptions options1 = new MarkerOptions();
options1.title("Destination");
options1.position(dstLatLng);
mapboxMap.addMarker(options);
mapboxMap.addMarker(options1);
navigationMapRoute = new NavigationMapRoute(null, mapView, map, R.style.NavigationMapRoute);
getRoute(originPosition, dstPosition);
}
});
}

Hide buttons in an activity after a while in android studio

I am working on a map application, using android studio.
I have a map activity and I need some buttons on my map, for example zoom in,zoom out,search,...
I want to hide these buttons after a while and show them again onClick.
but I don't know how to do that.
here is my code
MapActivity.java
package com.example.tourismproject;
import android.location.Location;
import android.content.IntentSender;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
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 MapsActivity extends FragmentActivity implements
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener {
public static final String TAG = MapsActivity.class.getSimpleName();
/*
* Define a request code to send to Google Play services
* This code is returned in Activity.onActivityResult
*/
private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;
private GoogleMap mMap; // Might be null if Google Play services APK is not available
private GoogleApiClient mGoogleApiClient;
private LocationRequest mLocationRequest;
private float zoomLevel = 15; //street view
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
setUpMapIfNeeded();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
// Create the LocationRequest object
mLocationRequest = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setInterval(10 * 1000) // 10 seconds, in milliseconds
.setFastestInterval(1000); // 1 second, in milliseconds
}
#Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
mGoogleApiClient.connect();
}
#Override
protected void onPause() {
super.onPause();
if (mGoogleApiClient.isConnected()) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
mGoogleApiClient.disconnect();
}
}
/**
* Sets up the map if it is possible to do so (i.e., the Google Play services APK is correctly
* installed) and the map has not already been instantiated.. This will ensure that we only ever
* call {#link #setUpMap()} once when {#link #mMap} is not null.
* <p/>
* If it isn't installed {#link SupportMapFragment} (and
* {#link com.google.android.gms.maps.MapView MapView}) will show a prompt for the user to
* install/update the Google Play services APK on their device.
* <p/>
* A user can return to this FragmentActivity after following the prompt and correctly
* installing/updating/enabling the Google Play services. Since the FragmentActivity may not
* have been completely destroyed during this process (it is likely that it would only be
* stopped or paused), {#link #onCreate(Bundle)} may not be called again so we should call this
* method in {#link #onResume()} to guarantee that it will be called.
*/
private void setUpMapIfNeeded() {
// Do a null check to confirm that we have not already instantiated the map.
if (mMap == null) {
// Try to obtain the map from the SupportMapFragment.
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
.getMap();
// Check if we were successful in obtaining the map.
if (mMap != null) {
setUpMap();
}
}
}
/**
* This is where we can add markers or lines, add listeners or move the camera. In this case, we
* just add a marker near Africa.
* <p/>
* This should only be called once and when we are sure that {#link #mMap} is not null.
*/
private void setUpMap() {
mMap.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title("Marker"));
}
private void handleNewLocation(Location location) {
Log.d(TAG, location.toString());
double currentLatitude = location.getLatitude();
double currentLongitude = location.getLongitude();
LatLng latLng = new LatLng(currentLatitude, currentLongitude);
//mMap.addMarker(new MarkerOptions().position(new LatLng(currentLatitude, currentLongitude)).title("Current Location"));
MarkerOptions options = new MarkerOptions()
.position(latLng)
.title("I am here!");
mMap.addMarker(options);
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, zoomLevel));
}
#Override
public void onConnected(Bundle bundle) {
Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (location == null) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
} else {
handleNewLocation(location);
}
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
/*
* Google Play services can resolve some errors it detects.
* If the error has a resolution, try sending an Intent to
* start a Google Play services activity that can resolve
* error.
*/
if (connectionResult.hasResolution()) {
try {
// Start an Activity that tries to resolve the error
connectionResult.startResolutionForResult(this, CONNECTION_FAILURE_RESOLUTION_REQUEST);
/*
* Thrown if Google Play services canceled the original
* PendingIntent
*/
} catch (IntentSender.SendIntentException e) {
// Log the error
e.printStackTrace();
}
} else {
/*
* If no resolution is available, display a dialog to the
* user with the error.
*/
Log.i(TAG, "Location services connection failed with code " + connectionResult.getErrorCode());
}
}
#Override
public void onLocationChanged(Location location) {
handleNewLocation(location);
}
}
and my XML file is :
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:map="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.tourismproject.MapsActivity" />
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
//hide buttons after 1 sec
yourbutton.setVisibility(false);
}
}, 1000);
someView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(button.getVisibility()==View.VISIBLE){
button.setVisibility(View.GONE);
} else {
button.setVisibility(View.VISIBLE);
}
}
});
Also for better usability you can add some fading animation with something like this:
ObjectAnimator alpha = ObjectAnimator.ofFloat(button, "alpha", 1, 0);
//alpha.setDelay(500);
//alpha.setDuration(1000);
alpha.start();
You can use
#Override
public void onClick(View v) {
button.setVisibility(false);
}
you can use
Thread.sleep(3000);//for three seconds
button.setVisibility(false);
to make it invisible after a while //in this case after three seconds
i hope this is helpful

Why isnt my location logging out in my Android app's onLocationChanged method?

I'm not getting any errors when running my application, but Im also not seeing any log messages. Heres the part of my code that is supposed to be logging the location:
#Override
public void onLocationChanged(Location location) {
mCurrentLocation = location;
mLastUpdateTime = DateFormat.getTimeInstance().format(new Date());
Log.i("location", location.toString());
// updateUI();
}
Heres my full class code:
package com.example.haotian.tutorial32;
import android.content.Intent;
import android.location.Location;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import java.text.DateFormat;
import java.util.Date;
public class MapsActivity extends FragmentActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {
protected GoogleApiClient mGoogleApiClient;
protected LocationRequest mLocationRequest;
protected Location mCurrentLocation;
protected String mLastUpdateTime;
protected TextView mLastUpdateTimeTextView;
protected TextView mLatitudeTextView;
protected TextView mLongitudeTextView;
public static final String TAG = "MapsActivity";
public static final int THUMBNAIL = 1;
private GoogleMap mMap; // Might be null if Google Play services APK is not available.
private Button picButton; //takes user to camera
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
setUpMapIfNeeded();;
createLocationRequest();
buildGoogleApiClient();
picButton = (Button) findViewById(R.id.photobutton);
picButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
#Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
}
/**
* Sets up the map if it is possible to do so (i.e., the Google Play services APK is correctly
* installed) and the map has not already been instantiated.. This will ensure that we only ever
* call {#link #setUpMap()} once when {#link #mMap} is not null.
* <p/>
* If it isn't installed {#link SupportMapFragment} (and
* {#link com.google.android.gms.maps.MapView MapView}) will show a prompt for the user to
* install/update the Google Play services APK on their device.
* <p/>
* A user can return to this FragmentActivity after following the prompt and correctly
* installing/updating/enabling the Google Play services. Since the FragmentActivity may not
* have been completely destroyed during this process (it is likely that it would only be
* stopped or paused), {#link #onCreate(Bundle)} may not be called again so we should call this
* method in {#link #onResume()} to guarantee that it will be called.
*/
private void setUpMapIfNeeded() {
// Do a null check to confirm that we have not already instantiated the map.
if (mMap == null) {
// Try to obtain the map from the SupportMapFragment.
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
.getMap();
// Check if we were successful in obtaining the map.
if (mMap != null) {
setUpMap();
}
}
}
/**
* This is where we can add markers or lines, add listeners or move the camera. In this case, we
* just add a marker near Africa.
* <p/>
* This should only be called once and when we are sure that {#link #mMap} is not null.
*/
private void setUpMap() {
mMap.addMarker(new MarkerOptions().position(new LatLng(20, 20)).title("EECS397/600"));
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
}
#Override
public void onConnected(Bundle connectionHint) {
startLocationUpdates();
}
#Override
public void onConnectionSuspended(int cause) {
}
#Override
public void onConnectionFailed(ConnectionResult result) {
}
#Override
public void onLocationChanged(Location location) {
mCurrentLocation = location;
mLastUpdateTime = DateFormat.getTimeInstance().format(new Date());
Log.i("location", location.toString());
// updateUI();
}
// private void updateUI() {
// mLatitudeTextView.setText(String.valueOf(mCurrentLocation.getLatitude()));
// mLongitudeTextView.setText(String.valueOf(mCurrentLocation.getLongitude()));
// mLastUpdateTimeTextView.setText(mLastUpdateTime);
// }
protected void startLocationUpdates() {
LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient, mLocationRequest, this);
}
protected synchronized void buildGoogleApiClient() {
Log.i(TAG, "Building GoogleApiClient");
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener((GoogleApiClient.OnConnectionFailedListener) this)
.addApi(LocationServices.API)
.build();
createLocationRequest();
}
protected void createLocationRequest() {
LocationRequest mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(10000);
mLocationRequest.setFastestInterval(5000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
}
You need to call the connect() method in order for onConnected() to be called, which is where you correctly start location updates.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
setUpMapIfNeeded();;
createLocationRequest();
buildGoogleApiClient();
mGoogleApiClient.connect(); //Add this line!
//................

android studio running app background running [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I'm working on an android app which tracks the distance you ran. I want to be able to use another app ,like a music app, at the same time. I didn't find any good tutorials on how to make the app run in the background, if anybody knows any good tutorials or an easy solution to make the app run in the background I would really apreciate if you would share it with me.
Application code:
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentSender;
import android.location.Location;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.common.SupportErrorDialogFragment;
import java.text.DateFormat;
import java.util.Date;
public class StepCounter extends FragmentActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {
// Request code to use when launching the resolution activity
private static final int REQUEST_RESOLVE_ERROR = 1001;
// Unique tag for the error dialog fragment
private static final String DIALOG_ERROR = "dialog_error";
// Bool to track whether the app is already resolving an error
private boolean mResolvingError = false;
//keys
GoogleApiClient mGoogleApiClient;
TextView mLatitudeText;
TextView mLongitudeText;
TextView mcLatitudeText;
TextView mcLongitudeText;
TextView mDistanceText;
Location mLastLocation;
Location mCurrentLocation;
double d=0.0;
double lat1;
double lat2;
double lon1;
double lon2;
double dlat;
double dlon;
double raz=6371000;
double a;
double c;
LocationRequest mLocationRequest;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_step_counter);
mLatitudeText = (TextView) findViewById(R.id.lat);
mLongitudeText = (TextView) findViewById(R.id.lon);
mcLatitudeText = (TextView) findViewById(R.id.llat);
mcLongitudeText = (TextView) findViewById(R.id.llon);
mDistanceText = (TextView) findViewById(R.id.dist);
mResolvingError = savedInstanceState != null
&& savedInstanceState.getBoolean(STATE_RESOLVING_ERROR, false);
createLocationRequest();
buildGoogleApiClient();
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
#Override
protected void onStart() {
super.onStart();
if(!mResolvingError)
mGoogleApiClient.connect();
}
#Override
protected void onStop() {
mGoogleApiClient.disconnect();
super.onStop();
}
public void onConnected(Bundle connectionHint) {
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
mGoogleApiClient);
mCurrentLocation = mLastLocation;
if (mLastLocation != null) {
mLatitudeText.setText(String.valueOf(mLastLocation.getLatitude()));
mLongitudeText.setText(String.valueOf(mLastLocation.getLongitude()));
}
//modified
startLocationUpdates();
}
//pana aici merge de aici vine partea cu update
protected void startLocationUpdates() {
LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient, mLocationRequest, this);
}
protected void createLocationRequest() {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(500);
mLocationRequest.setFastestInterval(500);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
#Override
public void onLocationChanged(Location location) {
mLastLocation = mCurrentLocation;
mCurrentLocation = location;
updateDistance();
updateUI();
}
public void updateUI()
{
mLatitudeText.setText(String.valueOf(mLastLocation.getLatitude()));
mLongitudeText.setText(String.valueOf(mLastLocation.getLongitude()));
mcLatitudeText.setText(String.valueOf(mCurrentLocation.getLatitude()));
mcLongitudeText.setText(String.valueOf(mCurrentLocation.getLongitude()));
}
public void updateDistance()
{
lat1=Math.toRadians(mLastLocation.getLatitude());
lat2=Math.toRadians(mCurrentLocation.getLatitude());
lon1=Math.toRadians(mLastLocation.getLongitude());
lon2=Math.toRadians(mCurrentLocation.getLongitude());
dlat=Math.toRadians(lat2-lat1);
dlon=Math.toRadians(lon2-lon1);
a = Math.sin(dlat/2) * Math.sin(dlat/2) + Math.cos(lat1) * Math.cos(lat2) * Math.sin(dlon/2) * Math.sin(dlon/2);
c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
d += raz * c;
mDistanceText.setText(String.valueOf(d));
}
//#Override
protected void onPause() {
super.onPause();
stopLocationUpdates();
}
protected void stopLocationUpdates() {
LocationServices.FusedLocationApi.removeLocationUpdates(
mGoogleApiClient, this);
}
#Override
public void onResume() {
super.onResume();
if (mGoogleApiClient.isConnected()) {
startLocationUpdates();
}
}
// De aici partea cu rezolvatu problemei
#Override
public void onConnectionSuspended(int i) {
//todo nust...
}
#Override
public void onConnectionFailed(ConnectionResult result) {
if (mResolvingError) {
// Already attempting to resolve an error.
return;
} else if (result.hasResolution()) {
try {
mResolvingError = true;
result.startResolutionForResult(this, REQUEST_RESOLVE_ERROR);
} catch (IntentSender.SendIntentException e) {
// There was an error with the resolution intent. Try again.
mGoogleApiClient.connect();
}
} else {
// Show dialog using GoogleApiAvailability.getErrorDialog()
showErrorDialog(result.getErrorCode());
mResolvingError = true;
}
}
// The rest of this code is all about building the error dialog
/* Creates a dialog for an error message */
private void showErrorDialog(int errorCode) {
// Create a fragment for the error dialog
ErrorDialogFragment dialogFragment = new ErrorDialogFragment();
// Pass the error that should be displayed
Bundle args = new Bundle();
args.putInt(DIALOG_ERROR, errorCode);
dialogFragment.setArguments(args);
dialogFragment.show(getFragmentManager(), "errordialog");
}
/* Called from ErrorDialogFragment when the dialog is dismissed. */
public void onDialogDismissed() {
mResolvingError = false;
}
/* A fragment to display an error dialog */
public static class ErrorDialogFragment extends DialogFragment {
public ErrorDialogFragment() { }
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Get the error code and retrieve the appropriate dialog
int errorCode = this.getArguments().getInt(DIALOG_ERROR);
return GoogleApiAvailability.getInstance().getErrorDialog(
this.getActivity(), errorCode, REQUEST_RESOLVE_ERROR);
}
#Override
public void onDismiss(DialogInterface dialog) {
((StepCounter) getActivity()).onDialogDismissed();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_RESOLVE_ERROR) {
mResolvingError = false;
if (resultCode == RESULT_OK) {
// Make sure the app is not already connected or attempting to connect
if (!mGoogleApiClient.isConnecting() &&
!mGoogleApiClient.isConnected()) {
mGoogleApiClient.connect();
}
}
}
}
private static final String STATE_RESOLVING_ERROR = "resolving_error";
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putBoolean(STATE_RESOLVING_ERROR, mResolvingError);
}
}
You can use Service for your requirement .
It's an application component that works for a long time in the
background and does not display the user interface. If another
application component starts the service and the user switches to
another application, the service can continue to run in the
background.
You can check sample demo android-service-example and android-service-example2
You could use the wakefulintentservice which runs in different intervals as you set them. There are some examples out there like here:
http://www.programcreek.com/java-api-examples/index.php?api=com.commonsware.cwac.wakeful.WakefulIntentService
This would be recommended, because its not save that your standard service keeps running when the screen is off while jogging.
As for your comment above, you need to bind to the service from your UI and then you are able to call methods on the service. Read the documentation...

google maps V2 my location issue

I put the following code inside a new class I created (I hope I did the right thing by creating a new class). I am trying to get the current location of the user to show up on my map. The one problem that is showing up is that it is saying that "basic_map" is not a valid field. All that I have right now is just the map itself. I hope someone can help me.
ps.. Sorry about how the code looks on here. I can't seem to get it fixed to look like real code all the way.
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.LocationSource;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.widget.Toast;
public class mylocation extends FragmentActivity implements LocationListener, LocationSource
{
/**
* Note that this may be null if the Google Play services APK is not available.
*/
private GoogleMap mMap;
private OnLocationChangedListener mListener;
private LocationManager locationManager;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.basic_map);
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
if(locationManager != null)
{
boolean gpsIsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
boolean networkIsEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if(gpsIsEnabled)
{
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000L, 10F, this);
}
else if(networkIsEnabled)
{
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 5000L, 10F, this);
}
else
{
//Show an error dialog that GPS is disabled.
}
}
else
{
//Show a generic error dialog since LocationManager is null for some reason
}
setUpMapIfNeeded();
}
#Override
public void onPause()
{
if(locationManager != null)
{
locationManager.removeUpdates(this);
}
super.onPause();
}
#Override
public void onResume()
{
super.onResume();
setUpMapIfNeeded();
if(locationManager != null)
{
mMap.setMyLocationEnabled(true);
}
}
/**
* Sets up the map if it is possible to do so (i.e., the Google Play services APK is correctly
* installed) and the map has not already been instantiated.. This will ensure that we only ever
* call {#link #setUpMap()} once when {#link #mMap} is not null.
* <p>
* If it isn't installed {#link SupportMapFragment} (and
* {#link com.google.android.gms.maps.MapView
* MapView}) will show a prompt for the user to install/update the Google Play services APK on
* their device.
* <p>
* A user can return to this Activity after following the prompt and correctly
* installing/updating/enabling the Google Play services. Since the Activity may not have been
* completely destroyed during this process (it is likely that it would only be stopped or
* paused), {#link #onCreate(Bundle)} may not be called again so we should call this method in
* {#link #onResume()} to guarantee that it will be called.
*/
private void setUpMapIfNeeded() {
// Do a null check to confirm that we have not already instantiated the map.
if (mMap == null)
{
// Try to obtain the map from the SupportMapFragment.
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
// Check if we were successful in obtaining the map.
if (mMap != null)
{
setUpMap();
}
//This is how you register the LocationSource
mMap.setLocationSource(this);
}
}
/**
* This is where we can add markers or lines, add listeners or move the camera. In this case, we
* just add a marker near Africa.
* <p>
* This should only be called once and when we are sure that {#link #mMap} is not null.
*/
private void setUpMap()
{
mMap.setMyLocationEnabled(true);
}
#Override
public void activate(OnLocationChangedListener listener)
{
mListener = listener;
}
#Override
public void deactivate()
{
mListener = null;
}
#Override
public void onLocationChanged(Location location)
{
if( mListener != null )
{
mListener.onLocationChanged( location );
//Move the camera to the user's location once it's available!
mMap.animateCamera(CameraUpdateFactory.newLatLng(new LatLng(location.getLatitude(), location.getLongitude())));
}
}
#Override
public void onProviderDisabled(String provider)
{
// TODO Auto-generated method stub
Toast.makeText(this, "provider disabled", Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderEnabled(String provider)
{
// TODO Auto-generated method stub
Toast.makeText(this, "provider enabled", Toast.LENGTH_SHORT).show();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras)
{
// TODO Auto-generated method stub
Toast.makeText(this, "status changed", Toast.LENGTH_SHORT).show();
}
}
Try this:
setContentView(R.layout.basic_map);
Set map:
map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
Layout: basic_map.xml
<fragment
android:id="#+id/map"
android:layout_width="match_parent"
android:layout_below="#id/lltop"
android:layout_height="match_parent"
class="com.google.android.gms.maps.MapFragment" />

Categories

Resources