【问题标题】:How to prompt user to enable gps如何提示用户启用 gps
【发布时间】:2016-07-25 11:25:42
【问题描述】:

我正在尝试提示用户启用 gps,我尝试了很多次来解决问题但无法清除它。我是 android 新手,任何人都可以帮助我........ 我的 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);
       }
     }
    }

我的 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>

【问题讨论】:

    标签: android android-layout gps android-webview


    【解决方案1】:

    实现 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();
        }
    }     
    

    显示对话框以打开设置:

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

    在您的 onCreate 方法调用中:

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

    并重写 onActivityResult 方法来测试用户是否正确激活了 GPS。

    @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】:

      完整示例:

      /**
       * 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();
      }
      

      这是文档:http://www.androidhive.info/2012/07/android-gps-location-manager-tutorial/(复制第 7 点)

      【讨论】:

      • 嗨 Alexandre Beaudet,我怎样才能得到设置包。因为它显示错误无法找到设置包。
      • @nlr_p 我很困惑,你只是复制并粘贴了整个代码吗?
      【解决方案3】:

      查看这个官方文档: https://developer.android.com/training/permissions/requesting.html 此外,该线程上接受的答案是我用来提示存储写访问的答案,它工作得非常好: Android 6.0 Marshmallow. Cannot write to SD Card 您只需要锻炼位置访问的关键字。

      【讨论】:

        【解决方案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();
            }
        

        上述代码的 onProviderDisabled() 将为您提供所需的流程。
        如果有用,请为答案投票!

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2011-08-27
          • 1970-01-01
          • 1970-01-01
          • 2023-03-23
          • 1970-01-01
          • 1970-01-01
          • 2014-04-26
          相关资源
          最近更新 更多