ConnectionResult=SERVICE_MISSING for google play s

2019-09-10 03:43发布

问题:

The google play services work fine for lollipop, but when it comes to kitkat and lower version it gives an ConnectionResult error=1, even though the google-play-services is installed on the device.

Here is my code.

The top-level Build.gradle:

    buildscript {
        repositories {
            jcenter()
        }
        dependencies {
            classpath 'com.android.tools.build:gradle:1.3.0'
            classpath 'com.google.gms:google-services:1.5.0-beta2'

            // NOTE: Do not place your application dependencies here; they belong
            // in the individual module build.gradle files
        }
    }

    allprojects {
        repositories {
            jcenter()
        }
    }

    task clean(type: Delete) {
        delete rootProject.buildDir
    }

Here is my build.gradle(app):

buildscript {
    repositories {
        maven { url 'https://maven.fabric.io/public' }
    }

    dependencies {
        classpath 'io.fabric.tools:gradle:1.+'
    }
}
apply plugin: 'com.android.application'
apply plugin: 'io.fabric'

repositories {
    maven { url 'https://maven.fabric.io/public' }
}

apply plugin: 'com.google.gms.google-services'

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.1"

    defaultConfig {
        applicationId "com.yembrace.android.app"
        minSdkVersion 19
        targetSdkVersion 21
        maxSdkVersion 22
        versionCode 4
        versionName "1.0.3"
        multiDexEnabled true

    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:23.0.1'
    compile 'com.android.support:design:23.0.1'

    compile 'com.google.android.gms:play-services-plus:8.3.0'
    compile "com.google.android.gms:play-services-gcm:8.3.0"

    compile 'com.mcxiaoke.volley:library:1.0.19'
    compile 'com.android.support:recyclerview-v7:23.1.0'
    compile 'de.hdodenhof:circleimageview:1.2.1'
    compile 'com.android.support:cardview-v7:23.1.0'

    //beacons sdk
    compile 'com.estimote:sdk:0.8.8@aar'

    compile 'com.github.clans:fab:1.6.2'

    //Cards
    compile 'com.github.gabrielemariotti.cards:cardslib-cards:2.1.0'


    compile('com.crashlytics.sdk.android:crashlytics:2.5.2@aar') {
        transitive = true;
    }
}

Here is the login file where I am calling google-play-services:

public class LoginActivity extends Activity implements
        View.OnClickListener,
        ActivityCompat.OnRequestPermissionsResultCallback,
        GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener {

    private static final String TAG = "TAG";
    private static final int RC_SIGN_IN = 1;
    private static final int RC_PERM_GET_ACCOUNTS = 2;
    private static final String KEY_IS_RESOLVING = "is_resolving";
    private static final String KEY_SHOULD_RESOLVE = "should_resolve";
    private GoogleApiClient mGoogleApiClient;
    private boolean mIsResolving = false;
    private boolean mShouldResolve = false;

    SharedPreferences sharedPreferences;
    private ViewPager mViewPager;
    PageIndicator mIndicator;
    private String message;
    private SignInButton google_signin;
    private ProgressBar progressBar;
    private ServiceUtils serviceUtils;
    private ProfileData profileData;
    private BroadcastReceiver mRegistrationBroadcastReceiver;
    private static final int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        {
            progressBar = (ProgressBar) findViewById(R.id.progress_bar);
            progressBar.setIndeterminate(true);
            progressBar.setVisibility(View.INVISIBLE);
        }
        profileData = new ProfileData();
        serviceUtils = new ServiceUtils(this);
        initGoogle();
        sharedPreferences = getSharedPreferences("app_pref", MODE_PRIVATE);

        if (savedInstanceState != null) {
            mIsResolving = savedInstanceState.getBoolean(KEY_IS_RESOLVING);
            mShouldResolve = savedInstanceState.getBoolean(KEY_SHOULD_RESOLVE);
        }

    }


    private void initGoogle() {
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(Plus.API)
                .addScope(new Scope(Scopes.PROFILE))
                .addScope(new Scope(Scopes.EMAIL))
                .build();

        google_signin = (SignInButton) findViewById(R.id.sign_in_button);
        google_signin.setSize(SignInButton.SIZE_WIDE);
        google_signin.setColorScheme(SignInButton.COLOR_DARK);
        for (int i = 0; i < google_signin.getChildCount(); i++) {
            View v = google_signin.getChildAt(i);

            if (v instanceof TextView) {
                TextView tv = (TextView) v;
                tv.setPadding(0, 0, 20, 0);
            }
        }

        google_signin.setOnClickListener(this);
    }

    private void updateUI(boolean isSignedIn) {
        if (isSignedIn) {
            Person currentPerson = Plus.PeopleApi.getCurrentPerson(mGoogleApiClient);
            if (currentPerson != null) {

                profileData.setEmail(Plus.AccountApi.getAccountName(mGoogleApiClient));
                profileData.setPlatform("google");
                if (currentPerson.hasName()) profileData.setFullName(currentPerson.getDisplayName());
                if (currentPerson.hasImage()) profileData.setProfileImgUrl(currentPerson.getImage().getUrl());
                if (currentPerson.hasId()) profileData.setPlatformProfileId(currentPerson.getId());
                if (currentPerson.hasCover() && currentPerson.getCover().hasCoverPhoto()) profileData.setProfileCoverUrl(currentPerson.getCover().getCoverPhoto().getUrl());
                if (currentPerson.hasBirthday()) profileData.setBirthday(currentPerson.getBirthday());
                if (currentPerson.hasGender()) profileData.setGender(String.valueOf(currentPerson.getGender()));
                if (currentPerson.hasRelationshipStatus()) profileData.setRelationshipStatus(String.valueOf(currentPerson.getRelationshipStatus()));
                if (currentPerson.hasAgeRange()){ profileData.setMaxAge(String.valueOf(currentPerson.getAgeRange().getMax()));profileData.setMinAge(String.valueOf(currentPerson.getAgeRange().getMin()));}
                SharedPreferences.Editor editor = sharedPreferences.edit();
                editor.putString("platform", profileData.getPlatform());
                editor.putString("userName", profileData.getFullName());
                editor.putString("userEmail", profileData.getEmail());
                editor.putString("profileImage", profileData.getProfileImgUrl());
                editor.putString("profileCover",profileData.getProfileCoverUrl());
                editor.commit();

                registerUser();

            } else {
                Log.d(TAG, "Null Person, check the api-key");
                handleError("Connection Error");
            }
        } else {
            Log.d(TAG, "In UpdateUI: User not signedIn");
            handleError("Connection Error");

        }
    }

    private void showSignedInUI() {
        updateUI(true);
    }

    @Override
    protected void onStop() {
        super.onStop();
        mGoogleApiClient.disconnect();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putBoolean(KEY_IS_RESOLVING, mIsResolving);
        outState.putBoolean(KEY_SHOULD_RESOLVE, mShouldResolve);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == RC_SIGN_IN) {
            if (resultCode != RESULT_OK) {
                mShouldResolve = false;
            }
            mIsResolving = false;
            mGoogleApiClient.connect();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) {
        if (requestCode == RC_PERM_GET_ACCOUNTS) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                showSignedInUI();
            } else {
                Log.d(TAG, "GET_ACCOUNTS Permission Denied.");
            }
        }
    }

    @Override
    public void onConnected(Bundle bundle) {
        Log.d(TAG, "onConnected:" + bundle);
        mShouldResolve = false;
        showSignedInUI();
    }

    @Override
    public void onConnectionSuspended(int i) {
        Log.w(TAG, "onConnectionSuspended:" + i);
    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {
        GooglePlayServicesUtil.getErrorDialog(connectionResult.getErrorCode(), this, 0).show();
        Log.d(TAG, "onConnectionFailed:" + connectionResult.getErrorCode());

        if (!mIsResolving && mShouldResolve) {
            if (connectionResult.hasResolution()) {
                try {
                    connectionResult.startResolutionForResult(this, RC_SIGN_IN);
                    mIsResolving = true;
                    Log.d(TAG, "Could not resolve ConnectionResult.");
                } catch (IntentSender.SendIntentException e) {
                    Log.d(TAG, "Could not resolve ConnectionResult.", e);
                    handleError("Connection Error");
                    mIsResolving = false;
                    mGoogleApiClient.connect();
                }
            } else {
                showErrorDialog(connectionResult);
            }
        } else {
            handleError("Connection Error");
        }
    }

    private void showErrorDialog(ConnectionResult connectionResult) {
        GoogleApiAvailability apiAvailability = GoogleApiAvailability.getInstance();
        int resultCode = apiAvailability.isGooglePlayServicesAvailable(this);

        if (resultCode != ConnectionResult.SUCCESS) {
            if (apiAvailability.isUserResolvableError(resultCode)) {
                apiAvailability.getErrorDialog(this, resultCode, RC_SIGN_IN,
                        new DialogInterface.OnCancelListener() {
                            @Override
                            public void onCancel(DialogInterface dialog) {
                                mShouldResolve = false;
                            }
                        }).show();
                Log.d(TAG, "In ShowError");
            } else {
                Log.d(TAG, "Google Play Services Error:" + connectionResult);
                Log.d(TAG, "In ShowError: " + apiAvailability.getErrorString(resultCode));
                handleError("Play Services not supported");
                mShouldResolve = false;
            }
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.sign_in_button:
                progressBar.setIndeterminate(true);
                progressBar.setVisibility(View.VISIBLE);
                if (!serviceUtils.checkInternet()) {
                    progressBar.setVisibility(View.INVISIBLE);
                    handleError("Connection Error");
                } else {
                    mShouldResolve = true;
                    mGoogleApiClient.connect();
                }
                break;
        }
    }

    private void registerUser() {
        Log.d(TAG, "LoginActivity:RegisterUser:Url: " + Config.user_login_url);
        StringRequest request = new StringRequest(Request.Method.POST,
                Config.user_login_url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        SharedPreferences.Editor editor = sharedPreferences.edit();
                        try {

                            progressBar.setVisibility(View.INVISIBLE);

                            JSONObject json_response = new JSONObject(response);
                            Log.d(TAG, response.toString());
                            message = json_response.getString("message");
                            if (message.equals("Inserted successfully") || message.equals("ReLogin"))
                                editor.putString("userID", json_response.getString("UserID"));
                            editor.commit();


                            Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                            intent.putExtra("page", 0);
                            if (message.equals("ReLogin"))
                                intent.putExtra("newUser", 1);
                            if (message.equals("Inserted successfully"))
                                intent.putExtra("newUser", 0);

                            startActivity(intent);
                            GCMRegister();

                        } catch (JSONException e) {
                            e.printStackTrace();
                            Log.d(TAG, "LoginActivity:RegisterUser:JSONException:: " + e.getMessage());
                            handleError("Connection Error");
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Log.d(TAG, "LoginActivity:RegisterUser:VolleyError: " + error.getMessage());
                        handleError("Connection Error");
                    }
                }) {

            @Override
            protected Map<String, String> getParams() {
                Map<String, String> params = new HashMap<String, String>();
                Log.d(TAG, "LoginActivity:RegisterUser:Post:" + profileData.getEmail() + ", " + profileData.getPlatform() + "," + profileData.getFullName() + "," + profileData.getGender() + "," + profileData.getMaxAge()+","+profileData.getEmail()+","+profileData.getBirthday()+","+profileData.getProfileCoverUrl());
                params.put("Email", profileData.getEmail());
                params.put("LoginPlatform", profileData.getPlatform());
                params.put("FullName", profileData.getFullName());
                params.put("ProfilePic", profileData.getProfileImgUrl());
                params.put("ProfileUrl", profileData.getPlatformProfileId());
                params.put("ProfileCoverUrl",profileData.getProfileCoverUrl());
                params.put("DOB", profileData.getBirthday());
                params.put("Gender",profileData.getGender());
                params.put("RelationshipStatus",profileData.getRelationshipStatus());
                params.put("MaxAge",profileData.getMaxAge());
                params.put("MinAge",profileData.getMinAge());
                params.put("UserIsActive", String.valueOf(1));
                params.put("UserDevice", "Android" + android.os.Build.VERSION.SDK_INT);
                return params;
            }

        };

        AppController.getInstance().addToRequestQueue(request);
    }

    private void GCMRegister() {
        mRegistrationBroadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
                boolean sentToken = sharedPreferences.getBoolean(Config.SENT_TOKEN_TO_SERVER, false);
                if (sentToken) {
                    Log.d(TAG, "register");
                } else {
                    Log.d(TAG, "token error");
                }
            }
        };

        if (checkPlayServices()) {
        Intent intent = new Intent(this, RegistrationIntentService.class);
        startService(intent);
        }
    }

    private boolean checkPlayServices() {
        GoogleApiAvailability apiAvailability = GoogleApiAvailability.getInstance();
        int resultCode = apiAvailability.isGooglePlayServicesAvailable(this);
        if (resultCode != ConnectionResult.SUCCESS) {
            if (apiAvailability.isUserResolvableError(resultCode)) {
                apiAvailability.getErrorDialog(this, resultCode, PLAY_SERVICES_RESOLUTION_REQUEST).show();
            } else {
                Log.i(TAG, "This device is not supported.");
                handleError("Play Services not supported");
            }
            return false;
        }
        return true;
    }

    @Override
    public void onResume() {
        mViewPager = (ViewPager) findViewById(R.id.view_pager);
        mIndicator = (CirclePageIndicator) findViewById(R.id.indicator);
        mViewPager.setAdapter(new ImageSlideAdapter(this, "SignIn"));
        mIndicator.setViewPager(mViewPager);
        super.onResume();
    }

    private void handleError(String msg) {
        progressBar.setVisibility(View.INVISIBLE);
        if(msg.equals("Play Services not supported"))
        {
            Toast.makeText(this,"Play Services not supported",Toast.LENGTH_LONG).show();
        }
        Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
    }



}

Can you suggest me where am i going wrong ?? should i downgrade my sdk version to make it compatible with kitkat ? Thanks.

回答1:

Check your kitkat device's play service app version. Maybe you should use older versions of play service library.

in your top-level build.gradle file:

classpath 'com.google.gms:google-services:1.3.0-beta1'

in your app's build.gradle file:

compile 'com.google.android.gms:play-services-plus:7.5.0'
compile "com.google.android.gms:play-services-gcm:7.5.0"