GooglePlayServicesUtil 대 GoogleApiAvailability


102

Android 앱에서 Google Play 서비스를 사용하려고합니다. Google 문서에 따르면 Google API를 사용하기 전에 사용할 수 있는지 확인해야합니다. 나는 그것을 확인하기 위해 어떤 방법을 찾았습니다. 내가 얻은 것은 다음과 같습니다.

private boolean checkPlayServices() {
int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (resultCode != ConnectionResult.SUCCESS) {
    if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
        GooglePlayServicesUtil.getErrorDialog(resultCode, this,
                PLAY_SERVICES_RESOLUTION_REQUEST).show();
    } else {
        Log.i(TAG, "This device is not supported.");
        finish();
    }
    return false;
}
return true;
}

하지만 Google Api GooglePlayServicesUtil 페이지로 이동하면 https://developers.google.com/android/reference/com/google/android/gms/common/GooglePlayServicesUtil

모든 기능이 더 이상 사용되지 않는다는 것을 알았습니다 . 예를 들어, 방법

GooglePlayServicesUtil.isGooglePlayServicesAvailable (지원 중단됨)

그리고 Google은 다음을 사용하는 것이 좋습니다.

GoogleApiAvailability.isGooglePlayServicesAvailable .

그러나 GoogleApiAvailability.isGooglePlayServicesAvailable을 사용하려고하면 오류 메시지가 표시됩니다.

여기에 이미지 설명 입력


GoogleApiAvailability는 어디에서 찾을 수 있습니까? 찾을 수 없습니다.
mcmillab

@mcmillab +1. 8.1.0에서 8.4.0으로 업그레이드 한 GooglePlayServicesUtil후 사라졌지 만 ( "부"업데이트에는 나쁜 습관처럼 보임 ) GoogleApiAvailability대체로 사용할 수 없습니다 .
spaaarky21

Firebase 체크 아웃으로 업데이트 할 때 : etivy.com/…
Dawid Drozd

답변:


203

해결책을 찾았습니다. 에서 GoogleApiAvailability의 동안, 모든 방법이 공개되어있어서 GooglePlayServicesUtil모든 방법 정적 공용 함수이다.

따라서 GoogleApiAvailability를 사용하는 올바른 방법은 다음과 같습니다.

private boolean checkPlayServices() {
    GoogleApiAvailability googleAPI = GoogleApiAvailability.getInstance();
    int result = googleAPI.isGooglePlayServicesAvailable(this);
    if(result != ConnectionResult.SUCCESS) {
        if(googleAPI.isUserResolvableError(result)) {
            googleAPI.getErrorDialog(this, result,
                    PLAY_SERVICES_RESOLUTION_REQUEST).show();
        }

        return false;
    }

    return true;
}

9
무엇입니까 : PLAY_SERVICES_RESOLUTION_REQUEST
Saman Sattari

12
private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
Ferrrmolina

7
임의의 정수입니다. 당신은 가치를 만들 수 있습니다.
Timmmm

4
일부는 9000 이상 뭔가 값을 설정하는 것을 선호
matthias_b_nz

12
이 전체 Google Play 서비스 라이브러리 디자인은 완전히 엉망입니다. 모든 결함이 있으며 문서가 부족할뿐만 아니라 따라 가기가 어렵습니다.
mr5

64

GooglePlayServicesUtil 클래스를 더 이상 사용하면 안됩니다!

예를 들어 GCM (또는 다른 Google 서비스)이 필요한 경우 GoogleApiAvailability 클래스를 대신 사용할 수있는 방법은 다음과 같습니다 .

public static final int REQUEST_GOOGLE_PLAY_SERVICES = 1972;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (savedInstanceState == null) {
        startRegistrationService();
    }
}

private void startRegistrationService() {
    GoogleApiAvailability api = GoogleApiAvailability.getInstance();
    int code = api.isGooglePlayServicesAvailable(this);
    if (code == ConnectionResult.SUCCESS) {
        onActivityResult(REQUEST_GOOGLE_PLAY_SERVICES, Activity.RESULT_OK, null);
    } else if (api.isUserResolvableError(code) &&
        api.showErrorDialogFragment(this, code, REQUEST_GOOGLE_PLAY_SERVICES)) {
        // wait for onActivityResult call (see below)
    } else {
        Toast.makeText(this, api.getErrorString(code), Toast.LENGTH_LONG).show();
    }
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    switch(requestCode) {
        case REQUEST_GOOGLE_PLAY_SERVICES:
            if (resultCode == Activity.RESULT_OK) {
                Intent i = new Intent(this, RegistrationService.class); 
                startService(i); // OK, init GCM
            }
            break;

        default:
            super.onActivityResult(requestCode, resultCode, data);
    }
}

최신 정보:

REQUEST_GOOGLE_PLAY_SERVICESonActivityResult()메서드 에서 참조 할 수있는 임의의 이름과 값을 가진 정수 상수입니다 .

또한 this.onActivityResult()위의 코드를 호출 해도 괜찮습니다 ( super.onActivityResult()다른 곳 에서도 호출 ).


2
"GooglePlayServicesUtil 클래스를 더 이상 사용해서는 안됩니다!"라고 주장하는 소스를 가리킬 수 있습니까? Google Play 서비스 API는 너무 혼란 스럽습니다.
Lachezar 2015

8
deprecated로 표시된 GooglePlayServicesUtil의 모든 메소드와 javadoc 상단의 GoogleApiAvailability 클래스 에서 GOOGLE_PLAY_SERVICES_PACKAGE상수 를 가져 오는 권장 사항 은 Google이 알려주는 방법 입니다. 더 이상 클래스를 사용하지 마세요 . GooglePlayServicesUtil
Alexander Farber 2015

3
기기에 GoogleApiAvailability클래스가 존재하지 않는 이전 버전의 Google Play 서비스가있는 경우 어떻게 되나요? 조건식 내에서도 클래스를 정적으로 참조하면 앱이 충돌하지 않습니까?
Kevin Krumwiede 2015

6
@Kevin Krumwiede GoogleApiAvailability는 클라이언트 라이브러리의 일부입니다. 따라서 코드가 앱으로 컴파일됩니다. => 걱정하지 마십시오.
WindRider

9
onActivityResult ()를 호출하면 안됩니다. 다른 활동이 결과를 반환 할 때 외부에서 호출됩니다.
Yar

10

대신 GoogleApiAvailability 를 사용해야 합니다.

GoogleApiAvailability googleApiAvailability = GoogleApiAvailability.getInstance(); 
int errorCode = googleApiAvailability.isGooglePlayServicesAvailable(this);

this를 나타냅니다 context.


9

기기에 Google Play 서비스 APK가 있는지 확인하세요. 그렇지 않은 경우 사용자가 Google Play 스토어에서 APK를 다운로드하거나 기기의 시스템 설정에서 활성화 할 수있는 대화 상자를 표시합니다.

public static boolean checkPlayServices(Activity activity) {
    final int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
    GoogleApiAvailability apiAvailability = GoogleApiAvailability.getInstance();
    int resultCode = apiAvailability.isGooglePlayServicesAvailable(activity);
    if (resultCode != ConnectionResult.SUCCESS) {
        if (apiAvailability.isUserResolvableError(resultCode)) {
            apiAvailability.getErrorDialog(activity, resultCode, PLAY_SERVICES_RESOLUTION_REQUEST)
                    .show();
        } else {
            Logger.logE(TAG, "This device is not supported.");
        }
        return false;
    }
    return true;
}

0

나는 이것을 BaseActivity 클래스에 재미로 추가하여 모든 곳에서 사용할 수 있습니다.

    fun checkGooglePlayServices(okAction : ()-> Unit , errorAction: (msg:String, isResolved:Boolean)-> Unit){
    val apiAvailability = GoogleApiAvailability.getInstance()
    val resultCode = apiAvailability.isGooglePlayServicesAvailable(this)
    if (resultCode != ConnectionResult.SUCCESS) {
        if (apiAvailability.isUserResolvableError(resultCode)) {
            apiAvailability.getErrorDialog(
                this,
                resultCode,
                PLAY_SERVICES_RESOLUTION_REQUEST
            ).show()
             // dialoe when click on ok should let user go to install/update play serices


            errorAction("dialog is shown" , true)

        } else {
          "checkGooglePlayServices  This device is not supported.".log(mTag)
            errorAction("This device is not supported",false)
        }
    }else{
        okAction()
    }
}

companion object {
    const val PLAY_SERVICES_RESOLUTION_REQUEST = 1425
}

이렇게 사용하세요

    (activity as? BaseActivity)?.checkGooglePlayServices({
        // ok so start map
        initializeMap()
    },
        { msg, isResolved ->
            if (!isResolved)
                context?.show(msg)

        }
    )

또는 원하는대로 사용자 지정할 수 있습니다.

당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.