如何在android中运行时检查用户是否启用或禁用了gps服务?

时间:2016-06-07 10:37:56

标签: android gps geolocation

我有一个应用程序,我需要获取用户的位置。因此,在应用程序开始时,我已检查GPS是否已打开。如果是,用户将轻松登录该应用程序。如果没有,将显示警告对话框,要求用户将其打开。如果用户拒绝,则应用将关闭,如果用户接受打开gps,则用户将导航到位置设置。但是,在用户到达位置设置后,我无法跟踪用户是否已打开gps。我怎么做 ?这是我的提醒箱代码:

if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            AlertDialog dialog = new     AlertDialog.Builder(login.this).setTitle("GPS NOT ENABLED!")
                    .setMessage("Plese, turn on your gps to login to the app")
                    .setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {

                            startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));

                            dialog.dismiss();


                        }
                    })
                    .setNegativeButton("No", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {

                            dialog.dismiss();

                            finish();

                        }
                    })

                    .setOnKeyListener(new DialogInterface.OnKeyListener() {
                        @Override
                        public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                            if (keyCode == KeyEvent.KEYCODE_BACK &&
                                    event.getAction() == KeyEvent.ACTION_UP &&
                                    !event.isCanceled()) {
                                dialog.dismiss();

                                finish();

                                return true;
                            }
                            return false;
                        }
                    })
                    .show();
            dialog.setCanceledOnTouchOutside(false);

        }

3 个答案:

答案 0 :(得分:1)

我以下面的方式实施的一种方式。

1.创建interface

public interface GpsInterface {
    void onGpsStatusChanged(boolean gpsStatus);
}

2.创建BroadcastReceiver

public class GpsListener extends BroadcastReceiver {

private GpsInterface gpsInterface = null;
private Context context;
public GpsListener(){}

public GpsListener(Context ctx, GpsInterface gpsInterface){
    this.gpsInterface = gpsInterface;
    this.context = ctx;
}

@Override
public void onReceive(Context context, Intent intent) {
    LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);

    if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){
        gpsInterface.onGpsStatusChanged(true);
    }else{
        gpsInterface.onGpsStatusChanged(false);
    }
}
}

3.在您的课程/活动中实施GpsInterface

public class MyActivity extends Activity implements GpsInterface{
    private GpsListener gpsListener;
    private boolean isGpsOn;

    //other stuff
}

    //in onCreate()
    IntentFilter mfilter = new IntentFilter(
            "android.location.PROVIDERS_CHANGED");
    gpsListener = new GpsListener(getActivity(), this);
    registerReceiver(gpsListener, mfilter);

在活动

中实施onGpsStatusChanged()方法
@Override
public void onGpsStatusChanged(boolean gpsStatus) {
    Logger.e("GPS STATUS", "ON " + gpsStatus);
    isGpsOn = gpsStatus;
}

4.在onDestroy()

中取消注册您的广播接收器
@Override
public void onDestroy() {
    unregisterReceiver(gpsListener);
}

希望这会有所帮助。

答案 1 :(得分:0)

使用以下代码检查是否启用了gps提供商和网络提供商。

LocationManager lm =     (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
boolean gps_enabled = false;
boolean network_enabled = false;

try {
gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
} catch(Exception ex) {}

try {
network_enabled = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
} catch(Exception ex) {}

if(!gps_enabled && !network_enabled) {
// notify user
AlertDialog.Builder dialog = new AlertDialog.Builder(context);
    dialog.setMessage(context.getResources().getString(R.string.gps_network_not_enabled));
    dialog.setPositiveButton(context.getResources().getString(R.string.open_location_settings), new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface paramDialogInterface, int     paramInt) {
            // TODO Auto-generated method stub
            Intent myIntent = new Intent(  Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            context.startActivity(myIntent);
            //get gps
        }
    });
dialog.setNegativeButton(context.getString(R.string.Cancel), new    DialogInterface.OnClickListener() {

        @Override
        public void onClick(DialogInterface paramDialogInterface, int paramInt) {
            // TODO Auto-generated method stub

        }
    });
    dialog.show();      
}

答案 2 :(得分:0)

这是一种在运行时检查GPS状态的简洁方法。

  1. 创建广播接收器

    private BroadcastReceiver mGPSConnectivityReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
    
        LocationManager manager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
    
        if (manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
    
        // GPS ON
    
        } else {
    
        // GPS OFF
    
        }
      }
    };
    
  2. 在onStart()

    中注册广播接收器
    @Override
    protected void onStart() {
        super.onStart();
    
        registerReceiver(mGPSConnectivityReceiver,
            new IntentFilter(LocationManager.PROVIDERS_CHANGED_ACTION));
    
    }
    
  3. 不要忘记在onStop()中取消注册接收器!

    @Override
    protected void onStop() {
        super.onStop();
    
        unregisterReceiver(mGPSConnectivityReceiver);
    
    }
    

    对于这个问题,这可能是最简单,最干净的解决方案。我真的希望它有所帮助!