GooglePlayServicesUtil vs GoogleApiAvailability

后端 未结 6 566
慢半拍i
慢半拍i 2020-11-28 20:25

I am trying to use Google Play Service in my Android app. As Google document says, we need to check if the Google API is available before using it. I have searched some way

6条回答
  •  旧巷少年郎
    2020-11-28 21:07

    The class GooglePlayServicesUtil shouldn't be used anymore!

    Here is how the class GoogleApiAvailability can be used instead - when for example GCM (or any other Google service) is needed:

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

    UPDATE:

    REQUEST_GOOGLE_PLAY_SERVICES is an integer constant with arbitrary name and value, which can be referred to in the onActivityResult() method.

    Also, calling this.onActivityResult() in the above code is okay (you also call super.onActivityResult() in the other place).

提交回复
热议问题