I'm using android studio to create an app, and so I implemented the google maps into my application and everything is working fine, all the implementation are there I triple checked, everything needed for it to operate is there, but my problem is that when I close my application for a long time and reopen the maps activity the fragment showing to me is a random one, no markers no locate button no objects just an empty map with the name of the countries. So I open the google maps application(official application) and close it, then try to reopen my google maps activity and everything reverts to normal, markers showing images are displayed, all the functions operate normally can someone tell me what may be the problem keep in mind everything is added, from an API key to the implementations in the graddle.app and the graddle.app.appname , and in the manifest the metadata is added and so on...thank you !
this is my map activity code where I added some NGOs locations and their images on the map:
import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.FragmentActivity;
import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.os.Bundle;
import android.widget.Toast;
import com.google.android.gms.location.FusedLocationProviderClient;
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.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.internal.ICameraUpdateFactoryDelegate;
import com.google.android.gms.maps.model.BitmapDescriptor;
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.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
public class map_act extends FragmentActivity implements OnMapReadyCallback {
Location currentLocation;
FusedLocationProviderClient fusedLocationProviderClient;
private static final int REQUEST_CODE = 101;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
fetchLastLocation();
}
private void fetchLastLocation() {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]
{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_CODE);
return;
}
Task<Location> task = fusedLocationProviderClient.getLastLocation();
task.addOnSuccessListener(new OnSuccessListener<Location>() {
#Override
public void onSuccess(Location location) {
if (location != null) {
currentLocation = location;
Toast.makeText(getApplicationContext(), "Your current location", Toast.LENGTH_SHORT).show();
SupportMapFragment supportMapFragment = (SupportMapFragment)
getSupportFragmentManager().findFragmentById(R.id.google_map);
supportMapFragment.getMapAsync(map_act.this);
}
}
});
}
#Override
public void onMapReady(GoogleMap googleMap) {
LatLng latLng = new LatLng(currentLocation.getLatitude(), currentLocation.getLongitude());
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
googleMap.setMyLocationEnabled(true);
googleMap.getUiSettings().setMyLocationButtonEnabled(true);
googleMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng,12));
LatLng Unicef1 = new LatLng(33.887837297007835, 35.50965848465925 );
googleMap.addMarker(new MarkerOptions().position(Unicef1).title("Unicef")
.icon(BitmapFromVector(getApplicationContext(), R.drawable.unicef1)));
LatLng Unicef2 = new LatLng(33.8865888125746, 35.48744276242378 );
googleMap.addMarker(new MarkerOptions().position(Unicef2).title("Unicef")
.icon(BitmapFromVector(getApplicationContext(), R.drawable.unicef1)));
LatLng Unicef3 = new LatLng( 34.42414282398606, 35.82587499823564 );
googleMap.addMarker(new MarkerOptions().position(Unicef3).title("Unicef")
.icon(BitmapFromVector(getApplicationContext(), R.drawable.unicef1)));
LatLng Unicef4 = new LatLng(33.27906495185468, 35.215073956249924 );
googleMap.addMarker(new MarkerOptions().position(Unicef4).title("Unicef")
.icon(BitmapFromVector(getApplicationContext(), R.drawable.unicef1)));
LatLng Wvision1 = new LatLng(33.86913267946954, 35.576261865395736 );
googleMap.addMarker(new MarkerOptions().position(Wvision1).title("World Vision")
.icon(BitmapFromVector(getApplicationContext(), R.drawable.worldvision1)));
LatLng Wvision2 = new LatLng(33.852201737887476, 35.57339217195826 );
googleMap.addMarker(new MarkerOptions().position(Wvision2).title("World vision")
.icon(BitmapFromVector(getApplicationContext(), R.drawable.worldvision1)));
LatLng Drc = new LatLng(33.892777808313056, 35.52051074415333 );
googleMap.addMarker(new MarkerOptions().position(Drc).title("Danish Refugee Council")
.icon(BitmapFromVector(getApplicationContext(), R.drawable.drc1)));
LatLng Nrc = new LatLng(33.897930365217256, 35.493069449639805 );
googleMap.addMarker(new MarkerOptions().position(Nrc).title("Norwegian Refugee Council")
.icon(BitmapFromVector(getApplicationContext(), R.drawable.nrc1)));
LatLng Oxfam1 = new LatLng(33.88743623998913, 35.50865875340152 );
googleMap.addMarker(new MarkerOptions().position(Oxfam1).title("OXFAM")
.icon(BitmapFromVector(getApplicationContext(), R.drawable.oxfam1)));
LatLng Oxfam2 = new LatLng(33.8484475255134, 35.91956548906049 );
googleMap.addMarker(new MarkerOptions().position(Oxfam2).title("OXFAM")
.icon(BitmapFromVector(getApplicationContext(), R.drawable.oxfam1)));
LatLng Oxfam3 = new LatLng(34.42224203429102, 35.827192870916654);
googleMap.addMarker(new MarkerOptions().position(Oxfam3).title("OXFAM")
.icon(BitmapFromVector(getApplicationContext(), R.drawable.oxfam1)));
LatLng Wfp = new LatLng(33.89447500501417, 35.50479228624766);
googleMap.addMarker(new MarkerOptions().position(Wfp).title("World Food Programme")
.icon(BitmapFromVector(getApplicationContext(), R.drawable.wfp1)));
LatLng Unhcr = new LatLng(33.897930365217256, 35.501776697895714);
googleMap.addMarker(new MarkerOptions().position(Unhcr).title("United Nations High Commissioner for Refugees")
.icon(BitmapFromVector(getApplicationContext(), R.drawable.unhcr1)));
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode){
case REQUEST_CODE:
if(grantResults.length>0 && grantResults[0]== PackageManager.PERMISSION_GRANTED){
fetchLastLocation();
}
break;
}
}
private BitmapDescriptor BitmapFromVector(Context context, int vectorResId) {
// below line is use to generate a drawable.
Drawable vectorDrawable = ContextCompat.getDrawable(context, vectorResId);
// below line is use to set bounds to our vector drawable.
vectorDrawable.setBounds(1, 1, vectorDrawable.getIntrinsicWidth(), vectorDrawable.getIntrinsicHeight());
// below line is use to create a bitmap for our
// drawable which we have added.
Bitmap bitmap = Bitmap.createBitmap(vectorDrawable.getIntrinsicWidth(), vectorDrawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
// below line is use to add bitmap in our canvas.
Canvas canvas = new Canvas(bitmap);
// below line is use to draw our
// vector drawable in canvas.
vectorDrawable.draw(canvas);
// after generating our bitmap we are returning our bitmap.
return BitmapDescriptorFactory.fromBitmap(bitmap);
}
}
here's my manifest code related to maps:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="#string/google_maps_key" />
In my build.graddle code I added :
google()
jcenter()
and here's my build.graddle.appname code:
apply plugin: 'com.android.application'
apply plugin: 'com.google.gms.google-services'
implementation "com.google.android.gms:play-services-maps:$googlePlayVersion"
implementation "com.google.android.gms:play-services-location:$googlePlayVersion"
So it turns out everything's coded right but there's one step that I didn't know of, I should've went into the google cloud platform and enabled the google maps SDK for my API key, so I went and did that and then redownloaded the google-services.json from the firebase (back-end I'm using) and replaced the old one in my app's folder with the new .json file. What was happening is that my API key added was not enabled for external use so when I was opening my google maps application(the official app) my App's API key was substituted by the google maps official one, and that's why my application's app wasn't functioning unless I open the google maps official application and then close it. So I did that and everything's working fine.
Related
I develop a simple app that shows me the imei of the device and the lat and long after pressing a button. Now, i want to save this data (lat, long, imei) in firestore, and i have some understanding problem where and what should i do to save this data into firestore.
I can't provide background with what i've done because i have understanding problem with what i should code.
package com.example.locatieimei;
import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Location;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.tasks.OnSuccessListener;
import org.w3c.dom.Text;
public class MainActivity extends AppCompatActivity {
private FusedLocationProviderClient client;
private TextView imei;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imei = findViewById(R.id.imei);
loadIMEI();
client = LocationServices.getFusedLocationProviderClient(this);
Button button = findViewById(R.id.Chk);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (ActivityCompat.checkSelfPermission(MainActivity.this,
Manifest.permission.ACCESS_FINE_LOCATION) !=
PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(MainActivity.this,
Manifest.permission.ACCESS_COARSE_LOCATION) !=
PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then
overriding
// public void onRequestPermissionsResult(int
requestCode, String[] permissions,
// int[]
grantResults)
// to handle the case where the user grants the
permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
client.getLastLocation().addOnSuccessListener(new
OnSuccessListener<Location>() {
#Override
public void onSuccess(Location location) {
if (location!=null){
TextView textView = findViewById(R.id.textView);
Double longitude = location.getLongitude();
Double latitude = location.getLatitude();
textView.setText(String.valueOf("latitudine"+longitude+
"\n"+"longitutine"+latitude));
}
}
});
}
});
}
public void loadIMEI() {
// Check if the READ_PHONE_STATE permission is already available.
if (ActivityCompat.checkSelfPermission(this,
Manifest.permission.READ_PHONE_STATE)
!= PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.READ_PHONE_STATE)) {
// get_imei_data();
} else {
ActivityCompat.requestPermissions(this, new String[]
{Manifest.permission.READ_PHONE_STATE},
MY_PERMISSIONS_REQUEST_READ_PHONE_STATE);
}
} else {
TelephonyManager mngr =
(TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
IMEI = mngr.getDeviceId();
imei.setText(mngr.getDeviceId());
// READ_PHONE_STATE permission is already been granted.
}
}
private String device_unique_id;
private static String IMEI;
private static final int MY_PERMISSIONS_REQUEST_READ_PHONE_STATE = 0;
}
i have some error when i try to add real time database from android
ERROR: Manifest merger failed : Attribute application#appComponentFactory value=(android.support.v4.app.CoreComponentFactory) from [com.android.support:support-compat:28.0.0] AndroidManifest.xml:22:18-91
is also present at [androidx.core:core:1.0.0] AndroidManifest.xml:22:18-86 value=(androidx.core.app.CoreComponentFactory).
Suggestion: add 'tools:replace="android:appComponentFactory"' to <application> element at AndroidManifest.xml:10:5-24:19 to override.
I had the same problem, you need to migrate your project to androidx, check out this reference, He will guide how to do this. https://developer.android.com/jetpack/androidx/migrate
click Refactor > Migrate to AndroidX in the menu.
I have application in Android Studio, that shows Google Map using Google Play Services. Application is written for Android 4.0.3. I have generated API key for Google Maps and placed it in google_maps_api.xml file according to this tutorial. Also I added entry for Google API key and permissions for GPS (to use location), Google Services and network in Android Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="vkalashnykov.org.mapygoogle">
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<!--
The ACCESS_COARSE/FINE_LOCATION permissions are not required to use
Google Maps Android API v2, but you must specify either coarse or fine
location permissions for the 'MyLocation' functionality.
-->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
<!--
The API key for Google Maps-based APIs is defined as a string resource.
(See the file "res/values/google_maps_api.xml").
Note that the API key is linked to the encryption key used to sign the APK.
You need a different API key for each encryption key, including the release key that is used to
sign the APK for publishing.
You can define the keys for the debug and release targets in src/debug/ and src/release/.
-->
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="#string/google_maps_key" />
<activity
android:name=".MapsActivity"
android:label="#string/title_activity_maps">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Also I added code for activity:
package vkalashnykov.org.mapygoogle;
import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Build;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.widget.Toast;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
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 OnMapReadyCallback, LocationListener {
private GoogleMap mMap;
private static final int LOCATION_MIN_TIME = 30 * 10;
private static final int LOCATION_MIN_DISTANCE = 1;
private LocationManager locationManager;
private Location currentLocation;
public static final String FIXED = "FIXED";
double szerokosc_g; // latitude
double dlugosc_g; // longitude
static final Integer LOCATION = 0x1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
if (Build.VERSION.SDK_INT >= 23) {
if (ActivityCompat.checkSelfPermission(MapsActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(MapsActivity.this, Manifest.permission.ACCESS_FINE_LOCATION)) {
ActivityCompat.requestPermissions(MapsActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, LOCATION);
} else {
//Metoda requestPermissions jest wywoływana aby uzytkownik mógł podjąć decyzję o nadaniu uprawnien
ActivityCompat.requestPermissions(MapsActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, LOCATION);
}
} else {
Toast.makeText(MapsActivity.this, " " + Manifest.permission.ACCESS_FINE_LOCATION + " uprawnienia zostały przyznane.", Toast.LENGTH_SHORT).show();
}
if (ActivityCompat.checkSelfPermission(MapsActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
Toast.makeText(MapsActivity.this, " " + Manifest.permission.ACCESS_FINE_LOCATION + "Uprawnienia nie zostały nadane", Toast.LENGTH_SHORT).show();
}
Toast.makeText(MapsActivity.this, "Wersja SDK systemu Android : " + Build.VERSION.SDK_INT , Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MapsActivity.this, "Wersja SDK systemu Android : " + Build.VERSION.SDK_INT , Toast.LENGTH_SHORT).show();
}
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)
{ return; }
szerokosc_g = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER).getLatitude();
dlugosc_g = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER).getLongitude();
LatLng pozycja = new LatLng(szerokosc_g,dlugosc_g); //adding position
mMap.addMarker(new MarkerOptions().position(pozycja).title("Pozycja"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(pozycja));
}
#Override
protected void onStart() {
super.onStart();
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if ( ContextCompat.checkSelfPermission( this, android.Manifest.permission.ACCESS_COARSE_LOCATION ) != PackageManager.PERMISSION_GRANTED ) {
ActivityCompat.requestPermissions( this, new String[] { android.Manifest.permission.ACCESS_COARSE_LOCATION },
LOCATION );
}
else
{ locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, LOCATION_MIN_TIME, LOCATION_MIN_DISTANCE, this);
Location gpsLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (gpsLocation != null) {
currentLocation = gpsLocation;
} else {
Location networkLocation = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (networkLocation != null) {
currentLocation = networkLocation;
} else {
currentLocation = new Location(FIXED);
currentLocation.setAltitude(1);
currentLocation.setLatitude(43.296482);
currentLocation.setLongitude(5.36978);
}
onLocationChanged(currentLocation);
}
}
}
#Override
public void onLocationChanged(Location location) {
szerokosc_g = location.getLatitude();
dlugosc_g = location.getLongitude();
LatLng pozycja = new LatLng(szerokosc_g, dlugosc_g);
mMap.clear();
mMap.addMarker(new MarkerOptions().position(pozycja).title("Pozycja"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(pozycja));
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
}
But all I get when run application is unexpected error: "Unfortunally application stopped." What is wrong or how I can check what is wrong with appplcation (on Android Studio there is no any message or logs about error)?
When i push android button "recents" and select my app again to go back to de app, the lifecycle of MapsActivity execute onCreate again and create a new instance of MapsActivity.
That´s ok, but the old MapsActivity still running in background and that´s a problem because both MapsActivity have counters and still running and counting with different values in the same variables, like independent new variables.
The counter is in onLocationChanged() and called as "clock".
onLocationChanged() update automaticaly ever 5 seconds.
example:
counter is running : 1, 2, 3, 4, 5, ...
at this point i push android button "recent" (the system execute onCreate)
counter still running like that : 6, 1, 7, 2, 8, 3, ...
at this point a push again android button "recent" (execute onCreate)
counter still running like that : 9, 4, 1, 10, 5, 2, 11, 6, 3, ...
I suppose the lifecycle of MapsActivity not destroy old activities.
I need only one sequencial counter running, and i guess the old MapsActivity must die :)
any idea to solve my problem ? Thanks a lot!
below the manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.sasse.myapplication">
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="#string/google_maps_key" />
<activity
android:name=".MapsActivity"
android:label="#string/title_activity_maps">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
layout activity_maps.xml
<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.sasse.myapplication.MapsActivity" />
Maps_activity
package com.example.sasse.myapplication;
import android.*;
import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks;
import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener;
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.OnMapReadyCallback;
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 LocationListener, ConnectionCallbacks, OnConnectionFailedListener, OnMapReadyCallback {
private static final String TAG = "MapsActivity";
private GoogleMap mMap;
protected GoogleApiClient mGoogleApiClient;
protected LocationRequest mLocationRequest;
public int clock = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
checkLocationPermission();
}
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// Add a marker in Sydney and move the camera
LatLng sydney = new LatLng(-34, 151);
mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
//Initialize Google Play Services
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(this,
android.Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
} else {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
}
public void onLocationChanged(Location location) {
clock++;
if (clock>=10) {
Toast.makeText(this, "clock : "+clock, Toast.LENGTH_SHORT).show();
clock=0;
}
Log.i(TAG, "= = = = = >>> clock : "+clock);
}
// ---------------------------------------------------------------------------------------------
// ---------------- VERIFICAÇÃO DA CONEXÃO COM O SERVIDOR DO GOOGLE MAPS-----------------------
// ---------------------------------------------------------------------------------------------
public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
public boolean checkLocationPermission() {
if (ContextCompat.checkSelfPermission(this,
android.Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// Asking user if explanation is needed
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
android.Manifest.permission.ACCESS_FINE_LOCATION)) {
// Show an explanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.
//Prompt the user once explanation has been shown
ActivityCompat.requestPermissions(this,
new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(this,
new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
}
return false;
} else {
return true;
}
}
public void onRequestPermissionsResult(int requestCode, #NonNull String permissions[], #NonNull int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_LOCATION: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted. Do the
// contacts-related task you need to do.
if (ContextCompat.checkSelfPermission(this,
android.Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
if (mGoogleApiClient == null) {
buildGoogleApiClient();
}
mMap.setMyLocationEnabled(true);
}
} else {
// Permission denied, Disable the functionality that depends on this permission.
Toast.makeText(this, "permission denied", Toast.LENGTH_LONG).show();
}
}
// other 'case' lines to check for other permissions this app might request.
// You can add here other case statements according to your requirement.
}
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mGoogleApiClient.connect();
}
public void onConnected(Bundle bundle) {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(5000);
mLocationRequest.setFastestInterval(5000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
}
public void onConnectionSuspended(int i) {
}
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
}
Try using launchMode="singleTop" for activity
I wrote and compiled the program below and ran it but the intended purpose, which is to display the speed to a textView doesn't function as far as i can tell from running it on my phone.
There are two location output variables, speed, and ourSpe because ourSpe came from a youtube video I watched and it didn't work, and speed comes from a stack overflow question I looked up. Both helped but neither is getting a result to print out ass I press the Button spedButt. I think I just wrote the code in the wrong order but I'm also not sure if I'm in using LocationManager right.
The layout file only has two textViews and a Button in a Relativelayoutbut stack overflow keeps giving me an error and I can't figure that one out either. I'm having a bad day.
Main Code
package com.example.vitaliy_2.safespeedalert;
import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class SpeedTest extends AppCompatActivity implements LocationListener {
TextView txt;
TextView txt_2;
Button spedButt;
float curSpe;
float speed;
Location l;
Location mLastLocation;
Location pCurrentLocation;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_speed_test);
txt = (TextView) findViewById(R.id.speed_display);
txt_2 = (TextView) findViewById(R.id.speed_display_2);
spedButt = (Button) findViewById(R.id.spedButt);
speed = 0;
LocationManager lm = (LocationManager)this.getSystemService(Context.LOCATION_SERVICE);
if (ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)!= PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_COARSE_LOCATION) !=PackageManager.PERMISSION_GRANTED) {return;}
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
this.onLocationChanged(null);
}
#Override
public void onLocationChanged(final Location location) {
l = location;
if (this.mLastLocation != null)
speed = (float )Math.sqrt(
Math.pow(pCurrentLocation.getLongitude() - mLastLocation.getLongitude(), 2)
+ Math.pow(pCurrentLocation.getLatitude() - mLastLocation.getLatitude(), 2)
) / (pCurrentLocation.getTime() - this.mLastLocation.getTime());
this.mLastLocation = pCurrentLocation;
spedButt.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
if(l == null){
txt.setText("-.- m/s");
txt_2.setText("-.- m/s");
}else{
if (pCurrentLocation.hasSpeed())
speed = pCurrentLocation.getSpeed();
curSpe = location.getSpeed();
String sent = speed + "m/s";
txt.setText(sent);
String sentTwo = curSpe + "m/s";
txt_2.setText(sentTwo);
}
}
});
}
Answering My own question, This code pops up automatically but there still needs to be a clause that asks for permission.
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
return;
}else{
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 0, this);
}
this.onLocationChanged(null);
I've tried to make an app that has a map activity that as soon as it is opened , the map starts on the users current location. I tried to use guides and help online but it seems that all of these guides are outdated because they have the onResume and onStart method by default in the maps activity and instead i have the onMapReady method and none of these methods. this is the code that i tried writing but it does not work(app crashes),
package com.imt.civilwatch;
import android.content.pm.PackageManager;
import android.location.Location;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
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.OnMapReadyCallback;
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.StringCharacterIterator;
public class MapActivity extends FragmentActivity implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
private GoogleMap mMap;
protected GoogleApiClient mGoogleApiClient;
Location mLastLocation;
private double mLatitudeText;
private double mLongitudeText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
protected void onStart() {
mGoogleApiClient.connect();
super.onStart();
}
protected void onStop() {
mGoogleApiClient.disconnect();
super.onStop();
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// Add a marker in Sydney and move the camera
LatLng sydney = new LatLng(32, 35);
mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
//mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
}
#Override
public void onConnected(Bundle connectionHint) {
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
mGoogleApiClient);
if (mLastLocation != null) {
mLatitudeText = (Double.valueOf(mLastLocation.getLatitude()));
mLongitudeText = (Double.valueOf(mLastLocation.getLongitude()));
LatLng last = new LatLng( mLatitudeText,mLongitudeText);
mMap.moveCamera(CameraUpdateFactory.newLatLng(last));
}
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
}
From the documentation of Google Maps Android API, the location data available to an Android device includes the current location of the device pinpointed using a combination of technologies - the direction and method of movement, and whether the device has moved across a predefined geographical boundary, or geofence.
Depending upon the needs of your application, you can choose between these options:
Using My Location layer that provides a simple way to display the
device's location on the map. It does not provide data.
Using Google Play services Location
API is
recommended for all programmatic requests for location data.
And using the
LocationSource
interface allows you to provide a custom location provider.
For more information, check this tutorial on how to get the current location:
How to get current location in Android Google Map
Google Map Tutorial in Android Studio: How to get current location in Android Google Map
The method onMapReady runs when the map's fragment is ready and displaying the map.
The onConnected method runs when the device successfully connects with Google Play Location service and (if available) gets your last known location.
If you don't want the camera moving to your current location, delete whats between this condition:
if(mLastLocation != null){...}
For maps, the camera is what's visible on screen. The method mMap.moveCamera(...) tells Map to center the view at specific LatLng.
If your map is ready before your phone connects with Google Play Location API, the current location visible will be this:
if (mLastLocation != null) {
mLatitudeText = (Double.valueOf(mLastLocation.getLatitude()));
mLongitudeText = (Double.valueOf(mLastLocation.getLongitude()));
LatLng last = new LatLng( mLatitudeText,mLongitudeText);
mMap.moveCamera(CameraUpdateFactory.newLatLng(last));
}
Hope I was clear.
See the CameraFactory docs to learn about camera manipulation on Maps: https://developers.google.com/android/reference/com/google/android/gms/maps/CameraUpdateFactory
Bro You Need The GoogleApiClient and LocationRequest for this , and also in manifest two users permission that are "ACCESS FINE LOCATION AND ACCESS COARSE LOCATION" and in order to get the current Location You need to do such something like this:
Include This in Manifest:-
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
--> And Current Location Code in Acticity will be like this:
--> Create These Two Variables Globely in the Activity:
GoogleApiClient mGoogleapiClient;
LocationRequest mUserLocationRequest;
--> Then Come To the #override Onconnected() and do like this :-
#Override
public void onConnected(Bundle bundle) {
mUserLocationRequest = LocationRequest.create();
/* Priority = High so that more Correct User Location will be Accessed
up to date information ot highest information get*/
/* Priority = Low if you Don't Want The Exect Location Of The User */
mUserLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
/*For every 1 min I have to Fetch My User Location*/
mUserLocationRequest.setInterval(1000);
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleapiClient, mUserLocationRequest, (LocationListener) MainActivity.this);
}
--> Now Impelents The LocationListener in Activity which implents the Method onLocationChanged(): and do such stuff in this , that will give you up to date info whenever user changes its Location:-
#Override
public void onLocationChanged(Location location) {
if (location == null)
{
Toast.makeText(this, "Sorry We Can't able to Get Your Current Location", Toast.LENGTH_SHORT).show();
}
else
{
LatLng latLng = new LatLng(location.getLatitude(),location.getLongitude());
CameraUpdate update = CameraUpdateFactory.newLatLngZoom(latLng,15);
mGoogleMap.animateCamera(update);
}
}