我的设备上的GPS位置出错

时间:2018-06-13 12:09:38

标签: java android gps location

我正在尝试获取设备位置并在Google地图上添加标记。如果我在虚拟设备上启动我的应用程序,它会在日志中显示我在美国的一个不寻常的位置(但我住在意大利)但不是地图和标记,当我在物理设备上启动应用程序时,它没有找到位置,但我可以在地图上看到坐标0纬度和0经度的标记。

这是我的MainActivity:

public class MainActivity extends AppCompatActivity {

    private Toolbar toolbar;
    private TabLayout tabLayout;
    private ViewPager viewPager;
    private LocationManager locationManager;
    private LocationListener locationListener;
    private double latitudine;
    private double longitudine;


    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        locationManager = (LocationManager) this.getSystemService(LOCATION_SERVICE);
        locationListener = new LocationListener() {
            @Override
            public void onLocationChanged(Location location) {
                Log.d("Location: ", location.toString());
                latitudine = location.getLatitude();
                longitudine = location.getLongitude();
            }

            @Override
            public void onStatusChanged(String provider, int status, Bundle extras) {

            }

            @Override
            public void onProviderEnabled(String provider) {

            }

            @Override
            public void onProviderDisabled(String provider) {

            }
        };

        if (Build.VERSION.SDK_INT < 23) {

            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;
            }
            locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);

        }else{

            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},1);

            }else{
                locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
            }

        }

        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        getSupportActionBar().setDisplayHomeAsUpEnabled(false);

        viewPager = (ViewPager) findViewById(R.id.viewpager);
        setupViewPager(viewPager);

        tabLayout = (TabLayout) findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(viewPager);
        tabLayout.getTabAt(0).setIcon(R.drawable.drone);
        tabLayout.getTabAt(1).setIcon(R.drawable.maps);
        tabLayout.getTabAt(2).setIcon(R.drawable.registracion);
        tabLayout.getTabAt(3).setIcon(R.drawable.meteo);
        tabLayout.getTabAt(4).setIcon(R.drawable.user);

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if(grantResults.length>0 && grantResults[0]== PackageManager.PERMISSION_GRANTED){
            if(ContextCompat.checkSelfPermission(this,Manifest.permission.ACCESS_FINE_LOCATION)==PackageManager.PERMISSION_GRANTED){
                locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
            }
        }
    }

    private void setupViewPager(ViewPager viewPager) {
        ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
        adapter.addFragment(new FirstFragment(), "");
        adapter.addFragment(new SecondFragment(latitudine,longitudine), "");
        adapter.addFragment(new ThirdFragment(), "");
        adapter.addFragment(new FourthFragment(), "");
        adapter.addFragment(new FifthFragment(), "");
        viewPager.setAdapter(adapter);
    }

    class ViewPagerAdapter extends FragmentPagerAdapter {
        private final List<Fragment> mFragmentList = new ArrayList<>();
        private final List<String> mFragmentTitleList = new ArrayList<>();

        public ViewPagerAdapter(FragmentManager manager) {
            super(manager);
        }

        @Override
        public Fragment getItem(int position) {
            return mFragmentList.get(position);
        }

        @Override
        public int getCount() {
            return mFragmentList.size();
        }

        public void addFragment(Fragment fragment, String title) {
            mFragmentList.add(fragment);
            mFragmentTitleList.add(title);
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return mFragmentTitleList.get(position);
        }
    }
}

那是SecondFragment,是应该是地图的片段:

public class SecondFragment extends Fragment implements OnMapReadyCallback {

    private GoogleMap mGoogleMap;
    private MapView mMapView;
    private View mView;
    private LatLng position;

    public SecondFragment() {
    }

    @SuppressLint("ValidFragment")
    public SecondFragment(double lat, double lon){
        position = new LatLng(lat,lon);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mView = inflater.inflate(R.layout.fragment_second, container, false);
        return mView;
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mMapView = (MapView) mView.findViewById(R.id.mapGoogle);
        if (mMapView != null) {
            mMapView.onCreate(null);
            mMapView.onResume();
            mMapView.getMapAsync(this);
        }
    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        MapsInitializer.initialize(getContext());
        mGoogleMap = googleMap;
        googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
        googleMap.addMarker(new MarkerOptions().position(position));
    }
}

这是我在物理设备上启动应用程序时的运行:

06/13 13:57:10: Launching app
$ adb install-multiple -r -t C:\Users\utente\AndroidStudioProjects\DroneMaster2\app\build\intermediates\split-apk\debug\dep\dependencies.apk C:\Users\utente\AndroidStudioProjects\DroneMaster2\app\build\intermediates\split-apk\debug\slices\slice_0.apk C:\Users\utente\AndroidStudioProjects\DroneMaster2\app\build\intermediates\split-apk\debug\slices\slice_2.apk C:\Users\utente\AndroidStudioProjects\DroneMaster2\app\build\intermediates\split-apk\debug\slices\slice_1.apk C:\Users\utente\AndroidStudioProjects\DroneMaster2\app\build\intermediates\split-apk\debug\slices\slice_4.apk C:\Users\utente\AndroidStudioProjects\DroneMaster2\app\build\intermediates\split-apk\debug\slices\slice_3.apk C:\Users\utente\AndroidStudioProjects\DroneMaster2\app\build\intermediates\split-apk\debug\slices\slice_5.apk C:\Users\utente\AndroidStudioProjects\DroneMaster2\app\build\intermediates\split-apk\debug\slices\slice_6.apk C:\Users\utente\AndroidStudioProjects\DroneMaster2\app\build\intermediates\split-apk\debug\slices\slice_7.apk C:\Users\utente\AndroidStudioProjects\DroneMaster2\app\build\intermediates\split-apk\debug\slices\slice_8.apk C:\Users\utente\AndroidStudioProjects\DroneMaster2\app\build\intermediates\split-apk\debug\slices\slice_9.apk C:\Users\utente\AndroidStudioProjects\DroneMaster2\app\build\intermediates\instant-run-apk\debug\app-debug.apk 
Split APKs installed
$ adb shell am start -n "com.example.utente.dronemaster/com.example.utente.dronemaster.MainActivity" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER
Client not ready yet..Connected to process 18521 on device huawei-ale_l21-QLF7N16A10004648
Capturing and displaying logcat messages from application. This behavior can be disabled in the "Logcat output" section of the "Debugger" settings page.
I/FirebaseInitProvider: FirebaseApp initialization unsuccessful
I/InstantRun: starting instant run server: is main process
I/art: Can not find class: Landroid/view/SearchEvent;
W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter 

android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
I/art: Can not find class: Landroid/widget/ViewStub;
       Can not find class: Landroid/webkit/ViewStub;
       Can not find class: Landroid/app/ViewStub;
W/Resources: Converting to string: TypedValue{t=0x12/d=0x0 a=3 r=0x7f09000a}
             Converting to string: TypedValue{t=0x12/d=0x0 a=3 r=0x7f090015}
W/Resources: Converting to string: TypedValue{t=0x12/d=0x0 a=3 r=0x7f090008}
W/Resources: Converting to string: TypedValue{t=0x1/d=0x7f0f0132 a=-1 r=0x7f0f0132}
W/Resources: Converting to string: TypedValue{t=0x12/d=0x0 a=3 r=0x7f09012e}
             Converting to string: TypedValue{t=0x1d/d=0xff125688 a=3 r=0x7f060032}
             Converting to string: TypedValue{t=0x5/d=0x1 a=3 r=0x7f070004}
             Converting to string: TypedValue{t=0x5/d=0x1 a=3 r=0x7f070003}
             Converting to string: TypedValue{t=0x5/d=0x3801 a=1 r=0x10500c9}
W/Resources: Converting to string: TypedValue{t=0x12/d=0x0 a=3 r=0x7f09011a}
W/Resources: Converting to string: TypedValue{t=0x12/d=0x0 a=3 r=0x7f09013c}
I/HwCust: Constructor found for class android.widget.HwCustTextViewImpl
I/art: Can not find class: Landroid/text/StaticLayout$Builder;
I/OpenGLRenderer: Initialized EGL, version 1.4
W/Resources: Converting to string: TypedValue{t=0x5/d=0x2401 a=1 r=0x10500ce}
             Converting to string: TypedValue{t=0x5/d=0x3001 a=1 r=0x10500d0}
W/art: Before Android 4.1, method int android.support.v7.widget.DropDownListView.lookForSelectablePosition(int, boolean) would have incorrectly overridden the package-private method in android.widget.ListView

这是我在虚拟设备上启动应用程序时的运行:

06/13 14:05:11: Launching app
$ adb install-multiple -r -t C:\Users\utente\AndroidStudioProjects\DroneMaster2\app\build\intermediates\resources\instant-run\debug\resources-debug.apk C:\Users\utente\AndroidStudioProjects\DroneMaster2\app\build\intermediates\split-apk\debug\dep\dependencies.apk C:\Users\utente\AndroidStudioProjects\DroneMaster2\app\build\intermediates\split-apk\debug\slices\slice_1.apk C:\Users\utente\AndroidStudioProjects\DroneMaster2\app\build\intermediates\split-apk\debug\slices\slice_2.apk C:\Users\utente\AndroidStudioProjects\DroneMaster2\app\build\intermediates\split-apk\debug\slices\slice_0.apk C:\Users\utente\AndroidStudioProjects\DroneMaster2\app\build\intermediates\split-apk\debug\slices\slice_3.apk C:\Users\utente\AndroidStudioProjects\DroneMaster2\app\build\intermediates\split-apk\debug\slices\slice_4.apk C:\Users\utente\AndroidStudioProjects\DroneMaster2\app\build\intermediates\split-apk\debug\slices\slice_5.apk C:\Users\utente\AndroidStudioProjects\DroneMaster2\app\build\intermediates\split-apk\debug\slices\slice_6.apk C:\Users\utente\AndroidStudioProjects\DroneMaster2\app\build\intermediates\split-apk\debug\slices\slice_8.apk C:\Users\utente\AndroidStudioProjects\DroneMaster2\app\build\intermediates\split-apk\debug\slices\slice_7.apk C:\Users\utente\AndroidStudioProjects\DroneMaster2\app\build\intermediates\split-apk\debug\slices\slice_9.apk C:\Users\utente\AndroidStudioProjects\DroneMaster2\app\build\intermediates\instant-run-apk\debug\app-debug.apk 
Split APKs installed
$ adb shell am start -n "com.example.utente.dronemaster/com.example.utente.dronemaster.MainActivity" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER
Client not ready yet..Waiting for process to come online
Connected to process 8921 on device Nexus_5X_API_27 [emulator-5554]
Capturing and displaying logcat messages from application. This behavior can be disabled in the "Logcat output" section of the "Debugger" settings page.
I/FirebaseInitProvider: FirebaseApp initialization unsuccessful
I/InstantRun: starting instant run server: is main process
I/zygote: NativeAlloc concurrent copying GC freed 2734(736KB) AllocSpace objects, 0(0B) LOS objects, 52% free, 1386KB/2MB, paused 16.542ms total 83.193ms
D/OpenGLRenderer: HWUI GL Pipeline
D/Location:: Location[gps 37.421998,-122.084000 hAcc=20 et=+2h46m24s907ms alt=0.0 vAcc=??? sAcc=??? bAcc=??? {Bundle[mParcelledData.dataSize=96]}]
W/GooglePlayServicesUtil: Google Play services out of date.  Requires 12211000 but found 11580470
I/chatty: uid=10080(com.example.utente.dronemaster) identical 3 lines
W/GooglePlayServicesUtil: Google Play services out of date.  Requires 12211000 but found 11580470
D/: HostConnection::get() New Host Connection established 0xa20a4dc0, tid 8947
I/zygote: android::hardware::configstore::V1_0::ISurfaceFlingerConfigs::hasWideColorDisplay retrieved: 0
I/OpenGLRenderer: Initialized EGL, version 1.4
D/OpenGLRenderer: Swap behavior 1
W/OpenGLRenderer: Failed to choose config with EGL_SWAP_BEHAVIOR_PRESERVED, retrying without...
D/OpenGLRenderer: Swap behavior 0
D/EGL_emulation: eglCreateContext: 0xa3a14960: maj 3 min 0 rcv 3
D/EGL_emulation: eglMakeCurrent: 0xa3a14960: ver 3 0 (tinfo 0xa113e210)
D/EGL_emulation: eglMakeCurrent: 0xa3a14960: ver 3 0 (tinfo 0xa113e210)
D/Location:: Location[gps 37.421998,-122.084000 hAcc=20 et=+2h46m25s706ms alt=0.0 vAcc=??? sAcc=??? bAcc=??? {Bundle[mParcelledData.dataSize=96]}]
D/Location:: Location[gps 37.421998,-122.084000 hAcc=20 et=+2h46m35s707ms alt=0.0 vAcc=??? sAcc=??? bAcc=??? {Bundle[mParcelledData.dataSize=96]}]
D/Location:: Location[gps 37.421998,-122.084000 hAcc=20 et=+2h46m45s707ms alt=0.0 vAcc=??? sAcc=??? bAcc=??? {Bundle[mParcelledData.dataSize=96]}]
D/Location:: Location[gps 37.421998,-122.084000 hAcc=20 et=+2h46m55s708ms alt=0.0 vAcc=??? sAcc=??? bAcc=??? {Bundle[mParcelledData.dataSize=96]}]
D/Location:: Location[gps 37.421998,-122.084000 hAcc=20 et=+2h47m5s709ms alt=0.0 vAcc=??? sAcc=??? bAcc=??? {Bundle[mParcelledData.dataSize=96]}]
D/Location:: Location[gps 37.421998,-122.084000 hAcc=20 et=+2h47m15s710ms alt=0.0 vAcc=??? sAcc=??? bAcc=??? {Bundle[mParcelledData.dataSize=96]}]

2 个答案:

答案 0 :(得分:0)

  

尝试使用此代码:

不要忘记在清单文件中添加权限

<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

用以下方式实现您的课程:

  

实现LocationListener,GoogleApiClient.ConnectionCallbacks,   ResultCallback,   GoogleApiClient.OnConnectionFailedListener

protected GoogleApiClient mGoogleApiClient;
protected LocationRequest locationRequest;

String latitude = "";
String longitude = "";

@Override
public void onCreate(Bundle savedInstanceState) {


  if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        return rootView;
    }
    mGoogleApiClient = new GoogleApiClient.Builder(getActivity())
            .addApi(LocationServices.API)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this).build();
    mGoogleApiClient.connect();
    locationRequest = LocationRequest.create();
    locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    locationRequest.setInterval(30 * 1000);
    locationRequest.setFastestInterval(5 * 1000);

    LocationManager locationManager = (LocationManager) getActivity()
            .getSystemService(Context.LOCATION_SERVICE);
    Criteria locationCritera = new Criteria();
    String providerName = locationManager.getBestProvider(locationCritera,
            true);
    if (providerName != null) {
        try {
            Location location = locationManager.getLastKnownLocation(providerName);
            latitude = location.getLatitude() + "";
            longitude = location.getLongitude() + "";
        } catch (Exception e) {
            latitude = "0";
            longitude = "0";
        }
    }


    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0,
            0, NearByFragment.this);


     }






@Override
public void onLocationChanged(Location location) {

    latitude = String.valueOf(location.getLatitude());
    longitude = String.valueOf(location.getLongitude());
    Log.e("lat", latitude + "");
    Log.e("log", longitude + "");

}

@Override
public void onStatusChanged(String provider, int status, Bundle extras) {

}

@Override
public void onProviderEnabled(String provider) {

}

@Override
public void onProviderDisabled(String provider) {

}


@Override
public void onConnected(@Nullable Bundle bundle) {
    LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
            .addLocationRequest(locationRequest);
    builder.setAlwaysShow(true);
    PendingResult<LocationSettingsResult> result =
            LocationServices.SettingsApi.checkLocationSettings(
                    mGoogleApiClient,
                    builder.build()
            );

    result.setResultCallback(this);
}

@Override
public void onConnectionSuspended(int i) {

}

@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

}

@Override
public void onResult(@NonNull LocationSettingsResult locationSettingsResult) {
    final Status status = locationSettingsResult.getStatus();
    switch (status.getStatusCode()) {
        case LocationSettingsStatusCodes.SUCCESS:

            // NO need to show the dialog;

            break;

        case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
            //  Location settings are not satisfied. Show the user a dialog

            try {
                // Show the dialog by calling startResolutionForResult(), and check the result
                // in onActivityResult().

                status.startResolutionForResult(getActivity(), 100);

            } catch (Exception e) {

                //failed to show
            }
            break;

        case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
            // Location settings are unavailable so not possible to show any dialog now
            break;
    }
}
public class MainActivity extends AppCompatActivity implements LocationListener, GoogleApiClient.ConnectionCallbacks, ResultCallback, GoogleApiClient.OnConnectionFailedListener{

    private Toolbar toolbar;
    private TabLayout tabLayout;
    private ViewPager viewPager;
    private LocationManager locationManager;
    private LocationListener locationListener;
    private double latitudine;
    private double longitudine;
protected GoogleApiClient mGoogleApiClient;
protected LocationRequest locationRequest;

String latitude = "";
String longitude = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
       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) {
       Toast.makeText(getActivity(),   "Permission Error...", Toast.LENGTH_LONG).show();
        return ;
    }
    mGoogleApiClient = new GoogleApiClient.Builder(MainActivity.this)
            .addApi(LocationServices.API)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this).build();
    mGoogleApiClient.connect();
    locationRequest = LocationRequest.create();
    locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    locationRequest.setInterval(30 * 1000);
    locationRequest.setFastestInterval(5 * 1000);

    LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    Criteria locationCritera = new Criteria();
    String providerName = locationManager.getBestProvider(locationCritera,
            true);
    if (providerName != null) {
        try {
            Location location = locationManager.getLastKnownLocation(providerName);
            latitude = location.getLatitude() + "";
            longitude = location.getLongitude() + "";
        } catch (Exception e) {
            latitude = "0";
            longitude = "0";
        }
    }


    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0,
            0, MainActivity.this);



        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        getSupportActionBar().setDisplayHomeAsUpEnabled(false);

        viewPager = (ViewPager) findViewById(R.id.viewpager);
        setupViewPager(viewPager);

        tabLayout = (TabLayout) findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(viewPager);
        tabLayout.getTabAt(0).setIcon(R.drawable.drone);
        tabLayout.getTabAt(1).setIcon(R.drawable.maps);
        tabLayout.getTabAt(2).setIcon(R.drawable.registracion);
        tabLayout.getTabAt(3).setIcon(R.drawable.meteo);
        tabLayout.getTabAt(4).setIcon(R.drawable.user);

    }

   // @Override
  //  public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
  //      super.onRequestPermissionsResult(requestCode, permissions, grantResults);
  //      if(grantResults.length>0 && grantResults[0]== PackageManager.PERMISSION_GRANTED){
  //          if(ContextCompat.checkSelfPermission(this,Manifest.permission.ACCESS_FINE_LOCATION)==PackageManager.PERMISSION_GRANTED){
  //              locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
  //          }
  //      }
  //  }


@Override
public void onLocationChanged(Location location) {

    latitude = String.valueOf(location.getLatitude());
    longitude = String.valueOf(location.getLongitude());
    Log.e("lat", latitude + "");
    Log.e("log", longitude + "");

}

@Override
public void onStatusChanged(String provider, int status, Bundle extras) {

}

@Override
public void onProviderEnabled(String provider) {

}

@Override
public void onProviderDisabled(String provider) {

}


@Override
public void onConnected(@Nullable Bundle bundle) {
    LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
            .addLocationRequest(locationRequest);
    builder.setAlwaysShow(true);
    PendingResult<LocationSettingsResult> result =
            LocationServices.SettingsApi.checkLocationSettings(
                    mGoogleApiClient,
                    builder.build()
            );

    result.setResultCallback(this);
}

@Override
public void onConnectionSuspended(int i) {

}

@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

}

@Override
public void onResult(@NonNull LocationSettingsResult locationSettingsResult) {
    final Status status = locationSettingsResult.getStatus();
    switch (status.getStatusCode()) {
        case LocationSettingsStatusCodes.SUCCESS:

            // NO need to show the dialog;

            break;

        case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
            //  Location settings are not satisfied. Show the user a dialog

            try {
                // Show the dialog by calling startResolutionForResult(), and check the result
                // in onActivityResult().

                status.startResolutionForResult(getActivity(), 100);

            } catch (Exception e) {

                //failed to show
            }
            break;

        case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
            // Location settings are unavailable so not possible to show any dialog now
            break;
    }
    private void setupViewPager(ViewPager viewPager) {
        ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
        adapter.addFragment(new FirstFragment(), "");
        adapter.addFragment(new SecondFragment(latitudine,longitudine), "");
        adapter.addFragment(new ThirdFragment(), "");
        adapter.addFragment(new FourthFragment(), "");
        adapter.addFragment(new FifthFragment(), "");
        viewPager.setAdapter(adapter);
    }

    class ViewPagerAdapter extends FragmentPagerAdapter {
        private final List<Fragment> mFragmentList = new ArrayList<>();
        private final List<String> mFragmentTitleList = new ArrayList<>();

        public ViewPagerAdapter(FragmentManager manager) {
            super(manager);
        }

        @Override
        public Fragment getItem(int position) {
            return mFragmentList.get(position);
        }

        @Override
        public int getCount() {
            return mFragmentList.size();
        }

        public void addFragment(Fragment fragment, String title) {
            mFragmentList.add(fragment);
            mFragmentTitleList.add(title);
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return mFragmentTitleList.get(position);
        }
    }
}

答案 1 :(得分:0)

当您在虚拟设备上运行GPS时,您需要通过虚拟设备侧栏上的“更多”设置自行输入GPS线。