How to prompt user to enable gps

﹥>﹥吖頭↗ 提交于 2021-02-04 08:09:10

问题


I am trying to prompt the user to enable gps, i tried many times to resolve issues but not able to clear it.I am new to android can any one please help me........ My mainactivity.java,

public class MainActivity extends AppCompatActivity {
private WebView view;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    WebView.setWebContentsDebuggingEnabled(true);
    WebView view = (WebView) this.findViewById(R.id.webView);
    view.loadUrl("https://google.com");
    view.getSettings().setJavaScriptEnabled(true);
    view.getSettings().setDomStorageEnabled(true);
    view.getSettings().setDatabaseEnabled(true);
    view.getSettings().setAppCacheEnabled(true);
    view.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
    view.getSettings().setUseWideViewPort(true);
    view.getSettings().setLoadWithOverviewMode(true);
    view.getSettings().setBuiltInZoomControls(false);
    view.getSettings().setAllowUniversalAccessFromFileURLs(true);
    view.getSettings().setAllowContentAccess(true);
    view.setWebChromeClient(new WebChromeClient());
    view.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
    view.setScrollbarFadingEnabled(false);
    view.getSettings().setBuiltInZoomControls(true);
    view.getSettings().setPluginState(PluginState.ON);
    view.getSettings().setAllowFileAccess(true);
    view.getSettings().setSupportZoom(true);
    CheckEnableGPS();
}
private void CheckEnableGPS(){
    String provider = Settings.Secure.getString(getContentResolver(),
            Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
    if(!provider.equals("")){
        //GPS Enabled
        Toast.makeText(AndroidEnableGPS.this, "GPS Enabled: " + provider,
                Toast.LENGTH_LONG).show();
       }else  {
          Intent intent = new Intent(Settings.ACTION_SECURITY_SETTINGS);
          startActivity(intent);
       }
     }
    }

my androidmanifest.xml,

  <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="test.test">
  <uses-permission android:name="android.permission.INTERNET"/>
  <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
  <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
   <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
  <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
  <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
  <uses-permission android:name="android.permission.CAMERA"/>
  <uses-feature android:name="android.hardware.camera" />
  <uses-permission android:name="android.permission.ACCESS_GPS" />
  <uses-permission android:name="android.permission.ACCESS_ASSISTED_GPS"   />
  <uses-permission android:name="android.permission.ACCESS_LOCATION" />
  <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
  <uses-permission android:name="android.permission.BLUETOOTH"/>
  <uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
  <application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

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

</manifest>

回答1:


Implement LocationListener :

@Override
public void onLocationChanged(Location location) {

}

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

}

@Override
public void onProviderEnabled(String provider) {

}

@Override
public void onProviderDisabled(String provider)
{
    if (provider.equals(LocationManager.GPS_PROVIDER))
    {
        showGPSDiabledDialog();
    }
}     

Show dialog to open Settings:

public void showGPSDiabledDialog() {
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setTitle("GPS Disabled");
    builder.setMessage("Gps is disabled, in order to use the application properly you need to enable GPS of your device");
    builder.setPositiveButton("Enable GPS", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            startActivityForResult(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS), GPS_ENABLE_REQUEST);
        }
    }).setNegativeButton("No, Just Exit", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {

        }
    });
    mGPSDialog = builder.create();
    mGPSDialog.show();
}

In your onCreate Method call :

LocationManager mLocationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
    return;
}
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);

And override onActivityResult method to test if the user activated GPS correctly.

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == GPS_ENABLE_REQUEST) {
        if (mLocationManager == null) {
            mLocationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
        }

        if (!mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            showGPSDiabledDialog();
        }
    } else {
        super.onActivityResult(requestCode, resultCode, data);
    }
}



回答2:


Full example :

/**
 * Function to check if best network provider
 * @return boolean
 * */
public boolean canGetLocation() {
    return this.canGetLocation;
}

/**
 * Function to show settings alert dialog
 * */
public void showSettingsAlert(){
    AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);

    // Setting Dialog Title
    alertDialog.setTitle("GPS is settings");

    // Setting Dialog Message
    alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");

    // Setting Icon to Dialog
    //alertDialog.setIcon(R.drawable.delete);

    // On pressing Settings button
    alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog,int which) {
            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            mContext.startActivity(intent);
        }
    });

    // on pressing cancel button
    alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
        dialog.cancel();
        }
    });

    // Showing Alert Message
    alertDialog.show();
}

Here is the doc : http://www.androidhive.info/2012/07/android-gps-location-manager-tutorial/ (copied point 7)




回答3:


Check this official document: https://developer.android.com/training/permissions/requesting.html Also, the accepted answer on this thread is the one I used to prompt for storage write access and it works perfectly fine: Android 6.0 Marshmallow. Cannot write to SD Card You only need to workout the keywords for location access.




回答4:


        public class MainActivity extends AppCompatActivity
                implements NavigationView.OnNavigationItemSelectedListener ,OnMapReadyCallback,LocationListener{

     protected static final String TAG = "MainActivity";
        protected static final int REQUEST_CHECK_SETTINGS = 0x1;

        Marker mCurrLocationMarker;
        GoogleMap mgooglemap;
        private LocationManager locationManager;


@Override
    public void onLocationChanged(Location 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("Current Position");
       // markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
      // mCurrLocationMarker = mgooglemap.addMarker(markerOptions);


        //move map camera
        mgooglemap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng,16));
mgooglemap.getMaxZoomLevel();
      //  locationManager.removeUpdates(this);
    }

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

    }

    @Override
    public void onProviderEnabled(String provider) {

    }

    @Override
    public void onProviderDisabled(String provider) {
        Toast.makeText(MainActivity.this, "Please Enable GPS", Toast.LENGTH_LONG).show();
    }

The onProviderDisabled() of the above code will provide you the required flow.
Pls upvote the answer if useful!



来源:https://stackoverflow.com/questions/38566490/how-to-prompt-user-to-enable-gps

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!