2017-04-06 61 views
-1

嗯,我基本上想這樣做,我希望能夠檢查GPS是否啓用,而我使用的地圖,我有這個代碼,但我不知道在哪裏檢查所以它總是:使用谷歌地圖查看GPS Android Studio

import android.content.Context; 
import android.content.DialogInterface; 
import android.content.Intent; 
import android.content.pm.PackageManager; 
import android.location.Criteria; 
import android.location.Location; 
import android.location.LocationManager; 
import android.os.Build; 
import android.provider.Settings; 
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 android.support.v4.content.ContextCompat; 
import android.support.v7.app.AlertDialog; 
import android.view.View; 
import android.widget.Toast; 

import com.google.android.gms.common.ConnectionResult; 
import com.google.android.gms.common.api.Api; 
import com.google.android.gms.common.api.GoogleApiClient; 
import com.google.android.gms.common.api.PendingResult; 
import com.google.android.gms.common.api.Status; 
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.BitmapDescriptor; 
import com.google.android.gms.maps.model.BitmapDescriptorFactory; 
import com.google.android.gms.maps.model.LatLng; 
import com.google.android.gms.maps.model.Marker; 
import com.google.android.gms.maps.model.MarkerOptions; 

import java.io.FileDescriptor; 
import java.io.PrintWriter; 
import java.util.concurrent.TimeUnit; 

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener { 

    private GoogleMap mMap; 
    GoogleApiClient mGoogleApiClient; 
    Location mLastLocation; 
    Marker mCurrLocationMarker; 
    LocationRequest mLocationRequest; 

    // LocationManager manager=(LocationManager) getSystemService(Context.LOCATION_SERVICE); 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_maps); 
     SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager() 
       .findFragmentById(R.id.map); 
     mapFragment.getMapAsync(this); 

     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; 
     } 
     /* if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER)){ 
      Toast.makeText(this, "Holap", Toast.LENGTH_LONG).show(); 
     }*/ 


    } 


    @Override 
    public void onMapReady(GoogleMap googleMap) { 
     mMap = googleMap; 
     mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID); 
     buildGoogleApiClient(); 
     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; 
     } 
     mMap.setMyLocationEnabled(true); 

    } 

    protected synchronized void buildGoogleApiClient() { 
     mGoogleApiClient = new GoogleApiClient.Builder(this) 
       .addConnectionCallbacks(this) 
       .addOnConnectionFailedListener(this) 
       .addApi(LocationServices.API) 
       .build(); 
     mGoogleApiClient.connect(); 
    } 


    public void onConnected(@Nullable Bundle bundle) { 
     mLocationRequest = new LocationRequest(); 
     mLocationRequest.setInterval(1000); 
     mLocationRequest.setFastestInterval(1000); 
     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); 
     }*/ 
     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, mLocationRequest, this); 
    } 


    public void onConnectionSuspended(int i) { 
     Toast.makeText(this, "Con Sus",Toast.LENGTH_LONG).show(); 
     habilitarGPS(); 
    } 


    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) { 
     Toast.makeText(this, "Con Fail",Toast.LENGTH_LONG).show(); 
    habilitarGPS(); 
    } 


    public void onLocationChanged(Location location) { 
     comprobargps(); 
     if (mLastLocation!=location) { 
      mLastLocation = location; 
      if (mCurrLocationMarker != null) { 
       mCurrLocationMarker.remove(); 
      } 

      LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude()); 
      MarkerOptions markerOptions = new MarkerOptions(); 
      markerOptions.position(latLng); 
      markerOptions.title("Current Position"); 

      markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA)); 
      mCurrLocationMarker = mMap.addMarker(markerOptions); 

      //Para mover la cámara 
      mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng)); 
      mMap.animateCamera(CameraUpdateFactory.zoomTo(11)); 

      if (mGoogleApiClient!=null) { 
       LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this); 
      } 
     } 
    } 


    /**************************************************************/ 

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

    public void onProviderEnabled(String provider) { 
    } 

    public void onProviderDisabled(String provider) { 
     habilitarGPS(); 
    } 

    public void habilitarGPS(){ 
     AlertDialog hey=cuadro(); 
     hey.show(); 
    } 

    public AlertDialog cuadro() { 
     AlertDialog.Builder builder = new AlertDialog.Builder(this); 
     builder.setTitle("GPS") 
       .setMessage("Debe habilitar el GPS") 
       .setPositiveButton("Aceptar", new DialogInterface.OnClickListener(){ 
        public void onClick(DialogInterface dialog, int which){ 
         Intent llamadaGPS=new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS); 
         startActivity(llamadaGPS); 
        } 
       }) 
       .setNegativeButton("Cancelar", new DialogInterface.OnClickListener() { 
        public void onClick(DialogInterface dialog, int which) { 
         textocancel(); 
        } 
       }); 

     return builder.create(); 

    } 

    public void textocancel(){ 
     Toast.makeText(this, "Cancelado", Toast.LENGTH_LONG).show(); 
    } 

    public void comprobargps(){ 
     int locmodo=0; 
     String locationProviders; 

     /* if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT){ 
      try{ 
       locmodo =Settings.Secure.getInt(getApplicationContext().getContentResolver(), Settings.Secure.LOCATION_MODE); 

      }*/ 
     //} 
    } 
} 

的應用程序不會跟隨用戶,用戶是在每一個時刻,但我真的不知道在哪裏,甚至我應該怎麼檢查是否GPS被激活

回答

0

您可以用此來檢查GPS是否啓用。

public static boolean isGPSEnabled(Activity activity) { 
     LocationManager lm = (LocationManager) activity.getSystemService(Context.LOCATION_SERVICE); 
     boolean gps_enabled = false; 
     boolean network_enabled = false; 

     try { 
      gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER); 
     } catch (Exception e) { 
      Logger.error(Constant.LOGTAG, "gps provider error : " + e.getMessage()); 
     } 

     try { 
      network_enabled = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER); 
     } catch (Exception e) { 
      Logger.error(Constant.LOGTAG, "network provider error : " + e.getMessage()); 
     } 

     return !(!gps_enabled && !network_enabled); 
    } 

活動

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

      if(isGPSEnabled(this)){ 
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager() 
        .findFragmentById(R.id.map); 
        mapFragment.getMapAsync(this); 

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

     } 
+0

但是......我應該在哪裏調用該方法?我的主要問題是我應該在哪裏檢查它,我不知道該怎麼做,所以它總是檢查提供程序是否啓用 – zaree2122

+0

在mapFragment.getMapAsync(this)之前檢查; – ZeroOne

+0

但是...這樣做,它只在應用程序的開始時檢查,當我啓動它時,但我需要它始終檢查 – zaree2122