도래울

Android GPS State 확인 본문

개발/Android

Android GPS State 확인

도래울 2016. 2. 5. 13:04

지도를 비롯 위치정보를 이용한 서비스 개발시 유용한 팁 한가지 알려드립니다.

그것은 GPS 연결여부를 체크하여 미연결시 연결설정 화면으로 이동시켜 주는 기능입니다.

소스는 참 간단하죠^^

    @Override
    public void onCreate(Bundle savedInstanceState) {
        ...
        String context = Context.LOCATION_SERVICE;
        locationManager = (LocationManager)getSystemService(context);
        if(!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            alertCheckGPS();
      }
        ...
    }

    private void alertCheckGPS() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage("Your GPS is disabled! Would you like to enable it?")
                .setCancelable(false)
                .setPositiveButton("Enable GPS",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                moveConfigGPS();
                            }
                    })
                .setNegativeButton("Do nothing",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                dialog.cancel();
                            }
                    });
        AlertDialog alert = builder.create();
        alert.show();
    }

    // GPS 설정화면으로 이동
    private void moveConfigGPS() {
        Intent gpsOptionsIntent = new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
        startActivity(gpsOptionsIntent);
    }


Comments