在支持Android Cupcake(1.5)的设备上,如何检查和激活GPS?


当前回答

在LocationListener中,实现onProviderEnabled和onProviderDisabled事件处理程序。当你调用requestLocationUpdates(…)时,如果手机上的GPS是禁用的,onProviderDisabled将被调用;如果用户启用GPS, onProviderEnabled将被调用。

其他回答

以下是步骤:

步骤1:创建在后台运行的服务。

步骤2:在Manifest文件中也需要以下权限:

android.permission.ACCESS_FINE_LOCATION

步骤3:编写代码:

 final LocationManager manager = (LocationManager)context.getSystemService    (Context.LOCATION_SERVICE );

if ( !manager.isProviderEnabled( LocationManager.GPS_PROVIDER ) )
  Toast.makeText(context, "GPS is disabled!", Toast.LENGTH_LONG).show(); 
else
  Toast.makeText(context, "GPS is enabled!", Toast.LENGTH_LONG).show();

第四步:或者你可以简单地使用:

LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE );
boolean statusOfGPS = manager.isProviderEnabled(LocationManager.GPS_PROVIDER);

步骤5:持续运行服务以监控连接。

Kotlin解决方案:

private fun locationEnabled() : Boolean {
    val locationManager = getSystemService(Context.LOCATION_SERVICE) as LocationManager
    return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)
}

最好的方法似乎如下:

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

    if ( !manager.isProviderEnabled( LocationManager.GPS_PROVIDER ) ) {
        buildAlertMessageNoGps();
    }

  private void buildAlertMessageNoGps() {
    final AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setMessage("Your GPS seems to be disabled, do you want to enable it?")
           .setCancelable(false)
           .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
               public void onClick(@SuppressWarnings("unused") final DialogInterface dialog, @SuppressWarnings("unused") final int id) {
                   startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
               }
           })
           .setNegativeButton("No", new DialogInterface.OnClickListener() {
               public void onClick(final DialogInterface dialog, @SuppressWarnings("unused") final int id) {
                    dialog.cancel();
               }
           });
    final AlertDialog alert = builder.create();
    alert.show();
}

下面是在我的情况下工作的片段

final LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE );
if ( !manager.isProviderEnabled( LocationManager.GPS_PROVIDER ) ) {
    buildAlertMessageNoGps();
}

`

是的,你可以检查以下是代码:

public boolean isGPSEnabled (Context mContext){
    LocationManager locationManager = (LocationManager)
                mContext.getSystemService(Context.LOCATION_SERVICE);
    return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
}