OnLocationChange不会提示任何Toast和日志

时间:2018-01-10 06:34:56

标签: android google-maps location

我在Fragment内的位置变化时显示当前地址时遇到问题。

即使我已尝试Toast,但我的屏幕上没有提示Toast。我可以知道我错过了什么代码吗?

我正在使用Geocoder获取当前位置的地址

  

在我的OnCreateView我有这个代码

 mGoogleApiClient = new GoogleApiClient.Builder(getActivity())
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(LocationServices.API)
            .build();

    mLocationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);`
  

在我的OnMapReady

mMapProximity = googleMap;
    mMapProximity.setBuildingsEnabled(true);
    mMapProximity.getUiSettings().setRotateGesturesEnabled(false);
    mMapProximity.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(12.405888, 123.273419), 6));
    if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity(), 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;
    }
    mMapProximity.setMyLocationEnabled(true);
    gettingCurrentLocation();
  

我有gettingCurrentLocation()函数,这是它的代码

public void gettingCurrentLocation(){

    gps = new GPSTracker(getContext());

    // check if GPS enabled
    if(gps.canGetLocation()){

        latitudeGPSorigin = gps.getLatitude();
        longitudeGPSorigin = gps.getLongitude();
        Log.e("here location",latitudeGPSorigin + " 34567890 " + longitudeGPSorigin);

        //Origin, where you are. Geo Location
        origin = new LatLng(longitudeGPSorigin,latitudeGPSorigin);


        geocoder = new Geocoder(getContext(),Locale.getDefault());
        try {
            address = geocoder.getFromLocation(latitudeGPSorigin, longitudeGPSorigin, 1);
            if(address != null && address.size() > 0) {


                String addresses = address.get(0).getAddressLine(0);
                String area = address.get(0).getAddressLine(1);
                String city = address.get(0).getAddressLine(2);

                String fulladdress = addresses + area + city;

                String trimmed_address = fulladdress.replace("null","");

                txt_current_location.setText(trimmed_address);
            }

        } catch (IOException e) {
            e.printStackTrace();
        }


    }else{
        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
                getContext());
        alertDialogBuilder
                .setMessage("GPS is disabled in your device. Enable it?")
                .setCancelable(false)
                .setPositiveButton("Enable GPS",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog,
                                                int id) {
                                Intent callGPSSettingIntent = new Intent(
                                        android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                                getContext().startActivity(callGPSSettingIntent);
                            }
                        });
        alertDialogBuilder.setNegativeButton("Cancel",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        dialog.cancel();
                    }
                });
        AlertDialog alert = alertDialogBuilder.create();
        alert.show();
    }
}
  

我测试了OnLocationChange(Location location)

Toast.makeText(getContext(), "test", Toast.LENGTH_SHORT).show();
    Toast.makeText(getActivity(), "testact", Toast.LENGTH_SHORT).show();
  

这是我的完整Android Manifest

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="ph.jti.com.proximity">

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

<!--
     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" />

<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">
    <activity android:name=".Activity.SplashScreen">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <activity android:name=".Activity.Mainpage"/>


    <meta-data
        android:name="com.google.android.geo.API_KEY"
        android:value="@string/google_maps_key" />

</application>

修改

  

添加OnConnected代码

startLocationUpdates();

    if (ActivityCompat.checkSelfPermission(getContext(), android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getContext(), 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;
    }
    mlocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);

    if (mlocation == null) {
        startLocationUpdates();
    }
    if (mlocation != null) {

        // mLatitudeTextView.setText(String.valueOf(mLocation.getLatitude()));
        //mLongitudeTextView.setText(String.valueOf(mLocation.getLongitude()));
    } else {
        Toast.makeText(getContext(), "Location not Detected", Toast.LENGTH_SHORT).show();
    }

startLocationUpdates

mLocationRequest = LocationRequest.create()
            .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
            .setInterval(UPDATE_INTERVAL)
            .setFastestInterval(FASTEST_INTERVAL);
    // Request location updates

    if (ActivityCompat.checkSelfPermission(getContext(), android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getContext(), 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;
    }
    LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient,
            mLocationRequest, this);

添加完整代码(抱歉凌乱)

https://ghostbin.com/paste/pg7et

2 个答案:

答案 0 :(得分:0)

在Fragment中使用getActivity()来获取Context ..

作为替代方案,您还可以使用getApplicationContext()来获取上下文

改变这个..

LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient,
        mLocationRequest, this);

LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient,
        mLocationRequest, getActivity());

答案 1 :(得分:0)

我已经解决了,我只是忘了添加OnStart方法

`@Override
public void onStart(){
    super.onStart();
     if(this.googleApiClient != null){
            this.googleApiClient.connect();
    }
}`