Google 地图仅在应用程序发送到后台时加载

问题描述 投票:0回答:1

我面临一个特殊的问题,我正在尝试将我的应用程序的过时依赖项更新为当前版本。在这样做时,我删除了

    implementation 'com.google.android.gms:play-services:12.0.1'
依赖项并添加了
implementation 'com.google.android.gms:play-services-maps:18.2.0'
依赖项,因为我目前只需要在我的应用程序中使用谷歌地图。这样做之后,我遇到了一个特殊的问题,当我尝试加载谷歌地图时,它无法加载并且可见灰屏。虽然我的
onMapReady
函数正在被调用。只有当我使用主页或菜单按钮将应用程序发送到后台并重新启动应用程序时,我才能看到地图。为什么会发生这种情况以及我该如何解决这个问题?.

这是我的活动课-

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

这是我的应用程序级别 gradle 文件 -

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

这是我的清单

<?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>
android google-maps location maps
1个回答
0
投票

我已通过降级至

'com.google.android.gms:play-services-maps:18.0.0' as I found the issue in 
版本 18.2.0` 暂时解决了此问题。地图现在正在正确加载。

© www.soinside.com 2019 - 2024. All rights reserved.