Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Google maps is only loading when app is being sent into background

I am facing a peculiar issue, I am trying to update outdated dependencies of my app to current versions. In doing so I removed implementation 'com.google.android.gms:play-services:12.0.1' dependency and added implementation 'com.google.android.gms:play-services-maps:18.2.0' dependency as I only need google maps in my app currently. After doing so I have faced a peculiar issue, when I am trying to load the google map, it does not load and a grey screen is visible. Although my onMapReady function is being called. It is only when I send the app into background using the home or menu button and relaunch the app, I can see the map. Why is this happening and what do I do to solve this?.

Here is my Activity class-

public class WhereToBuyActivity extends AppCompatActivity implements OnMapReadyCallback,
        LocationListener {

    private GoogleMap mMap;
    Location mLastLocation;
    Marker mCurrLocationMarker;
    LocationRequest mLocationRequest;
    List<Address> Addresses = new ArrayList<>();
    Context context  = this;
    SharedPreferences.Editor editor;
    MarkerOptions  markerOptions;
    private ProgressDialog pDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_where_to_buy);

        getSupportActionBar().setDisplayShowCustomEnabled(true);
        getSupportActionBar().setDisplayShowTitleEnabled(false);
        getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.WHITE));

        LayoutInflater mInflater = LayoutInflater.from(this);
        View mCustomView = mInflater.inflate(R.layout.activity_map_title_bar, null);

        ActionBar.LayoutParams layout = new ActionBar.LayoutParams(ActionBar.LayoutParams.MATCH_PARENT, ActionBar.LayoutParams.MATCH_PARENT);
        getSupportActionBar().setCustomView(mCustomView,layout);
        getSupportActionBar().setDisplayShowCustomEnabled(true);

        TextView actionbarTitle = (TextView) mCustomView.findViewById(R.id.activityMapTitle);
        actionbarTitle.setText("Where to Buy");
        actionbarTitle.setTypeface(Typeface.DEFAULT_BOLD);
        actionbarTitle.setTextColor(Color.BLACK);

        TextView actionbarLoad = (TextView) mCustomView.findViewById(R.id.activityMapLoad);
        actionbarLoad.setText("Reload");

        actionbarLoad.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new DownloadXmlTask().execute();
            }
        });

        if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            checkLocationPermission();
        }

        // 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);

    }

    public void init(){
        Log.e("TAG","fetching XML");
        String url="http://fontaineintl.com/mobile_app_files/location.xml";
        UTF8StringRequest stringRequest = new UTF8StringRequest(Request.Method.GET, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {
                            Addresses=XmlParser.parseMapData(response);
                            //Log.e("TAG","Addresses = " + Addresses);
                            setMapData(Addresses);
                        } catch (XmlPullParserException e) {

                        } catch (IOException e) {
                            //Show Error Message
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                showAlertDialog(WhereToBuyActivity.this,"No Internet connection","You must be connected to the internet to use this feature ",false);

            }
        });
        stringRequest.setRetryPolicy(new DefaultRetryPolicy(
                1000*60*3,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        CustomVolleyRequest.getInstance(getApplicationContext()).addToRequestQueue(stringRequest);
    }

    public void setMapData(List Addresses) {
        Gson gson = new Gson();
        String jsonMapData = gson.toJson(Addresses);
        //Log.e("TAG","jsonMapDataSet = " + jsonMapData);
        SharedPreferences sharedPref = getSharedPreferences(getResources().getString(R.string.sharedPrefName), Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPref.edit();
        editor.putString("mapData", jsonMapData);
        editor.commit();
        addMarkers();
    }

    public void addMarkers()
    {
        SharedPreferences sharedPref = context.getSharedPreferences(context.getResources().getString(R.string.sharedPrefName), Context.MODE_PRIVATE);
        editor = sharedPref.edit();
        String jsonMapData = sharedPref.getString("mapData",null);
        //Log.e("TAG","jsonMapDataMarkers = " + jsonMapData);
        LatLng latLng;

        if(jsonMapData!=null) {
            Gson gson = new Gson();
            final List<Address> addressList = gson.fromJson(jsonMapData,
                    new TypeToken<List<Address>>() {
                    }.getType());
            Log.e("TAG","addressList = " + addressList.size());
            for (int i = 0; i < addressList.size(); i++) {
                String latitude = addressList.get(i).getLatitude();
                String longitude = addressList.get(i).getLongitude();
                String title = addressList.get(i).getName();
                String area = addressList.get(i).getArea();
                String city = addressList.get(i).getCity();
                String phoneNo = addressList.get(i).getPhone();
                String street = addressList.get(i).getStreet();
                String zip = addressList.get(i).getZip();
                if(latitude != null && !latitude.isEmpty() && longitude != null && !longitude.isEmpty() ) {
                    double latVal = Double.parseDouble(latitude);
                    double longVal = Double.parseDouble(longitude);

                    latLng = new LatLng(latVal, longVal);
                    markerOptions = new MarkerOptions();
                    markerOptions.position(latLng);
                    markerOptions.title(title);
                    markerOptions.snippet(phoneNo +"\n" +
                            area +"\n"
                            + city + ", " + street + " " + zip);
                    markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));

                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if(mMap != null) {
                                mMap.addMarker(markerOptions);
                                mMap.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() {

                                    @Override
                                    public View getInfoWindow(Marker arg0) {
                                        return null;
                                    }

                                    @Override
                                    public View getInfoContents(Marker marker) {

                                        LinearLayout info = new LinearLayout(context);
                                        info.setOrientation(LinearLayout.VERTICAL);

                                        TextView title = new TextView(context);
                                        title.setTextColor(Color.BLACK);
                                        title.setGravity(Gravity.CENTER);
                                        title.setTypeface(null, Typeface.BOLD);
                                        title.setText(marker.getTitle());

                                        TextView snippet = new TextView(context);
                                        snippet.setTextColor(Color.BLACK);
                                        snippet.setGravity(Gravity.CENTER);
                                        snippet.setText(marker.getSnippet());

                                        info.addView(title);
                                        info.addView(snippet);

                                        return info;
                                    }
                                });
                            }
                        }
                    });
                }
            }
        }
    }

    class DownloadXmlTask extends AsyncTask<Void, Void, Void> {
        //ProgressDialog d;
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(context);
            pDialog.setMessage("Downloading store data...");
            pDialog.setCancelable(false);
            showpDialog();
            /*d = new ProgressDialog(WhereToBuyActivity.this);
            d.setMessage("Downloading store data...");
            d.setCancelable(false);
            d.show();*/
        }

        @Override
        protected Void doInBackground(Void... params) {
            init();
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
            hidepDialog();
        }
    }

    private void showpDialog() {
        if (!pDialog.isShowing())
            pDialog.show();
    }

    private void hidepDialog() {
        if (pDialog.isShowing())
            pDialog.dismiss();
    }


    /**
     * 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_NORMAL);


        mMap.getUiSettings().setMyLocationButtonEnabled(true);

        Log.e("TAG","mMap = Yes");
        //Initialize Google Play Services
        if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (ContextCompat.checkSelfPermission(this,
                    android.Manifest.permission.ACCESS_FINE_LOCATION)
                    == PackageManager.PERMISSION_GRANTED) {
                mMap.setMyLocationEnabled(true);
            }
        }
        else {
            mMap.setMyLocationEnabled(true);
        }

        SharedPreferences sharedPref = getSharedPreferences(getResources().getString(R.string.sharedPrefName), Context.MODE_PRIVATE);
        editor = sharedPref.edit();
        String mapData = sharedPref.getString("mapData","");
        //mapData=null;
        if(mapData!=null && !mapData.isEmpty()) {
            addMarkers();
        }
        else {
            init();
        }
    }

    /*
    @Override
    public void onConnected(Bundle bundle) {

        mLocationRequest = new LocationRequest();
        mLocationRequest.setInterval(1000);
        mLocationRequest.setFastestInterval(500);
        mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
        if (ContextCompat.checkSelfPermission(this,
                android.Manifest.permission.ACCESS_FINE_LOCATION)
                == PackageManager.PERMISSION_GRANTED) {
            LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
        }

    }


    @Override
    public void onConnectionSuspended(int i) {

    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {

    }

     */

    @Override
    public void onLocationChanged(Location location) {

        mLastLocation = location;
        if (mCurrLocationMarker != null) {
            mCurrLocationMarker.remove();
        }

        //Place current location marker
        LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
        MarkerOptions markerOptions = new MarkerOptions();
        markerOptions.position(latLng);
        markerOptions.title("My Location");
        markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
        mCurrLocationMarker = mMap.addMarker(markerOptions);

        //move map camera
//        mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
//        mMap.animateCamera(CameraUpdateFactory.zoomTo(14));

        //Move the camera over to USA
        mMap.moveCamera(CameraUpdateFactory.newLatLng(new LatLng(39.5, -98.35)));
        mMap.animateCamera(CameraUpdateFactory.zoomTo(3));

    }

    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;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           String permissions[], 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) {
                        mMap.setMyLocationEnabled(true);
                    }

                } else {

                    // Permission denied, Disable the functionality that depends on this permission.
                    Toast.makeText(this, "permission denied", Toast.LENGTH_LONG).show();
                }
                return;
            }

            // other 'case' lines to check for other permissions this app might request.
            // You can add here other case statements according to your requirement.
        }
    }

    public void showAlertDialog(Context context, String title, String message, Boolean status) {
        AlertDialog alertDialog = new AlertDialog.Builder(context).create();
        alertDialog.setTitle(title);
        alertDialog.setMessage(message);
        //alertDialog.setIcon((status) ? R.drawable.success : R.drawable.fail);

        alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                finish();
            }
        });
        alertDialog.show();
    }

    @Override
    protected void onStart() {
        super.onStart();
        Log.d("START","WTB STARTED");
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.d("RESUME","WTB RESUMED");
    }

    @Override
    protected void onStop() {
        super.onStop();
        Log.d("STOP","WTB STOPPED");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.d("DESTROY","WTB DESTROY");
    }
}

Here is my app level gradle file -

apply plugin: 'com.android.application'

android {
    compileSdkVersion 33
    buildToolsVersion '30.0.2'
    defaultConfig {
        applicationId "com.ft.fifthwheel"
        minSdkVersion 19
        targetSdkVersion 33
        versionCode 6
        versionName "1.6"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        multiDexEnabled true
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
    implementation 'com.google.android.gms:play-services-location:21.1.0'
    androidTestImplementation('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    implementation 'com.android.support:appcompat-v7:26.1.0'
    implementation 'com.github.barteksc:android-pdf-viewer:2.7.0'
    implementation 'com.google.android.gms:play-services-maps:18.2.0'
    implementation 'com.android.volley:volley:1.1.1'
    implementation 'com.google.code.gson:gson:2.8.5'
    implementation 'com.android.support:design:26.1.0'
    def multidex_version = "2.0.1"
    implementation "androidx.multidex:multidex:$multidex_version"
    androidTestImplementation 'junit:junit:4.12'
}

Here is my manifest

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.ft.fifthwheel">

    <uses-feature android:name="android.hardware.camera" android:required= "true" />
    <uses-feature
        android:name="android.hardware.location.gps"
        android:required="false" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_MEDIA_IMAGES"/>
    <uses-permission android:name="android.permission.READ_MEDIA_VIDEO"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.CAMERA" />
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <!--
         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.
         android:icon="@drawable/logo"
    -->
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

    <queries>
        <intent>
            <action android:name="android.media.action.IMAGE_CAPTURE" />
        </intent>
    </queries>

    <application
        android:name=".model.Multi_Dex"
        android:allowBackup="true"
        android:hardwareAccelerated="false"
        android:icon="@drawable/logo"
        android:label="@string/app_name"
        android:largeHeap="true"
        android:supportsRtl="true"
        android:usesCleartextTraffic="true"
        android:requestLegacyExternalStorage="true"
        android:theme="@style/AppTheme">

        <uses-library android:name="org.apache.http.legacy" android:required="false" />
        <provider
            android:name="androidx.core.content.FileProvider"
            android:authorities="com.ft.fifthwheel.fileprovider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/file_paths"></meta-data>
        </provider>


        <activity android:name=".activity.PhotoViewerActivity"></activity>
        <activity android:name=".activity.MainActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".activity.WebViewActivity"
            android:theme="@style/Theme.AppCompat.Light"
            android:exported="true"/>
        <activity android:name=".activity.ContactActivity"
            android:exported="false"/>
        <!--
             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=".activity.WhereToBuyActivity"
            android:label="@string/title_activity_where_to_buy" />
        <!--
 ATTENTION: This was auto-generated to add Google Play services to your project for
     App Indexing.  See https://g.co/AppIndexing/AndroidStudio for more information.

        <meta-data
            android:name="com.google.android.gms.version"
            android:value="@integer/google_play_services_version" />
        -->
        <activity android:name=".activity.PdfViewActivity"
            android:exported="false"/>
        <activity android:name=".activity.PdfViewOnlineActivity"
            android:exported="true"/>
        <activity android:name=".activity.RepairActivity"
            android:exported="false"/>
        <activity android:name=".activity.MediaLibraryActivity"
            android:exported="true"/>
        <activity android:name=".activity.SubCategoryActivity"
            android:exported="false"/>
        <activity android:name=".activity.DocumentActivity"
            android:exported="false"/>
        <activity android:name=".activity.LibraryPdfViewActivity"
            android:exported="false"/>
        <activity android:name=".activity.VideoActivity"
            android:exported="false"/>
        <activity
            android:name=".activity.VideoViewActivity"
            android:screenOrientation="landscape"
            android:exported="false"></activity>
    </application>

</manifest>
like image 626
Zarar Mahmud Avatar asked Nov 01 '25 19:11

Zarar Mahmud


2 Answers

I have temporarily fixed this issue by downgrading to 'com.google.android.gms:play-services-maps:18.0.0' as I found the issue in version 18.2.0. The map is loading properly now. Any other solution or feedback will be appreciated.

like image 184
Zarar Mahmud Avatar answered Nov 04 '25 11:11

Zarar Mahmud


Had the same issue in certain mobile models after switching to the new maps implementation and upgrading the maps dependency version to 18.2.0. Downgrading the maps dependency version didn't work.

Enabling hardware acceleration in the manifest fixed the issue for me.

<application
...
android:hardwareAccelerated="true"
...>

If you dont want to enable hard acceleration for the entire app then can enable it just for the maps activity.

<application
...
android:hardwareAccelerated="false"
...>
<activity
    ...
    android:hardwareAccelerated="true"
    ...>
</activity>
like image 37
Arun Avatar answered Nov 04 '25 11:11

Arun



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!