85

Application Crashes every time I run it on my phone. Is there something wrong? It says Unfortunately "appname" has stopped working. I have also tried other approaches to checking for googleplay services but it always crashes. I updated my google play services and have a working google map v2 working perfectly. Any solutions to this code? It crashes on my phone running android 4.1.2 and on my AVD.

package com.example.checkgoogleplayproject;

import android.app.Activity;
import android.app.Dialog;
import android.os.Bundle;
import android.view.Menu;
import android.widget.TextView;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;

public class MainActivity extends Activity {

    @Override
    protected void onResume() {
        super.onResume();

        // Getting reference to TextView to show the status
        TextView tvStatus = (TextView)findViewById(R.id.tv_status);

        // Getting status
        int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getBaseContext());

        // Showing status
        if(status==ConnectionResult.SUCCESS)
            tvStatus.setText("Google Play Services are available");
        else{
            tvStatus.setText("Google Play Services are not available");
            int requestCode = 10;
            Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this, requestCode);
            dialog.show();
        }
    }

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

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
}
user3144836
  • 4,060
  • 3
  • 27
  • 27

9 Answers9

153

To check if GooglePlayServices available or not, Use GoogleApiAvailability.isGooglePlayServicesAvailable(), As GooglePlayServicesUtil.isGooglePlayServicesAvailable() deprecated.

public boolean isGooglePlayServicesAvailable(Context context){
    GoogleApiAvailability googleApiAvailability = GoogleApiAvailability.getInstance();
    int resultCode = googleApiAvailability.isGooglePlayServicesAvailable(context);
    return resultCode == ConnectionResult.SUCCESS;  
}

Update: Check if google play service available, If google play service is not available and error is recoverable then open a dialog to resolve an error.

public boolean isGooglePlayServicesAvailable(Activity activity) {
    GoogleApiAvailability googleApiAvailability = GoogleApiAvailability.getInstance();
    int status = googleApiAvailability.isGooglePlayServicesAvailable(activity);
    if(status != ConnectionResult.SUCCESS) {
        if(googleApiAvailability.isUserResolvableError(status)) {
              googleApiAvailability.getErrorDialog(activity, status, 2404).show();
        }
        return false;
    }
    return true;
}
Dhaval Patel
  • 10,119
  • 5
  • 43
  • 46
20

I dont know where to post this but difficulty in correct workflow of google play services checking is mind blowing, I am using some custom classes, but you may get a point...

protected boolean checkPlayServices() {
    final int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(activity());
    if (resultCode != ConnectionResult.SUCCESS) {
        if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
            Dialog dialog = GooglePlayServicesUtil.getErrorDialog(resultCode, activity(),
                    PLAY_SERVICES_RESOLUTION_REQUEST);
            if (dialog != null) {
                dialog.show();
                dialog.setOnDismissListener(new OnDismissListener() {
                    public void onDismiss(DialogInterface dialog) {
                        if (ConnectionResult.SERVICE_INVALID == resultCode) activity().finish();
                    }
                });
                return false;
            }
        }
        new CSAlertDialog(this).show("Google Play Services Error",
                "This device is not supported for required Goole Play Services", "OK", new Call() {
                    public void onCall(Object value) {
                        activity().finish();
                    }
                });
        return false;
    }
    return true;
}
Renetik
  • 5,887
  • 1
  • 47
  • 66
14

Add this method to your Splash Screen; Your app won't start at all if you don't have Google Play Services updated or installed.

Dialog errorDialog;

private boolean checkPlayServices() {

        GoogleApiAvailability googleApiAvailability = GoogleApiAvailability.getInstance();

        int resultCode = googleApiAvailability.isGooglePlayServicesAvailable(this);

        if (resultCode != ConnectionResult.SUCCESS) {
            if (googleApiAvailability.isUserResolvableError(resultCode)) {

                if (errorDialog == null) {
                    errorDialog = googleApiAvailability.getErrorDialog(this, resultCode, 2404);
                    errorDialog.setCancelable(false);
                }

                if (!errorDialog.isShowing())
                    errorDialog.show();

            }
        }

        return resultCode == ConnectionResult.SUCCESS;
    }

and call it only on resume

@Override
protected void onResume() {
    super.onResume();
    if (checkPlayServices()) {
        startApp();
    }
}
Pedro Varela
  • 2,296
  • 1
  • 26
  • 32
  • Para la versión en español pues ir a este link https://medium.com/@pedro_varela/verificar-google-play-services-7e8890d8b49a – Pedro Varela Apr 25 '20 at 23:35
9

You set change checkPlayServices in read doc in new 2016 google samples for google services

enter image description here

if (checkPlayServices()) {
            // Start IntentService to register this application with GCM.
            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.");
                finish();
            }
            return false;
        }
        return true;
    }
sindyoke
  • 474
  • 1
  • 11
  • 16
Pong Petrung
  • 1,437
  • 17
  • 14
8

Change

int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getBaseContext());

to

int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getApplicationContext();
Shayden117
  • 252
  • 1
  • 3
  • 17
  • This method has been deprecated already. Use his `GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(getApplicationContext())` – Kidus Tekeste Jun 02 '20 at 15:17
7

As far as I know this is the minimal required code for checking for Google Play services on start of app in a splash screen like activity. Similar to Dhavel's answer, but without unnecessary code.

You can verify it works for all cases by simply passing a custom result code to the getErrorDialog method. All result codes are listed here. It's important to use onResume since it is called after returning to the app after updating Google Play services in Google Play etc.

class MainActivity : AppCompatActivity() {

    override fun onResume() {
        super.onResume()
        if (checkGooglePlayServices()) {
            startActivity(Intent(this, HomeActivity::class.java))
        }
    }

    private fun checkGooglePlayServices(): Boolean {
        val availability = GoogleApiAvailability.getInstance()
        val resultCode = availability.isGooglePlayServicesAvailable(this)
        if (resultCode != ConnectionResult.SUCCESS) {
            availability.getErrorDialog(this, resultCode, 0).show()
            return false
        }
        return true
    }
    
}
Simon Bengtsson
  • 7,573
  • 3
  • 58
  • 87
6

Thanks guys for your responses. I just figured it out from my LogCat. I had to include this in my Android Manifest.

<application>
<meta-data
        android:name="com.google.android.gms.version"
        android:value="@integer/google_play_services_version" />
...

user3144836
  • 4,060
  • 3
  • 27
  • 27
1

You can check for Play Services presence like this:

/**
 * Check if correct Play Services version is available on the device.
 *
 * @param context
 * @param versionCode
 * @return boolean
 */
public static boolean checkGooglePlayServiceAvailability(Context context, int versionCode) {

    // Query for the status of Google Play services on the device
    int statusCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(context);

    if ((statusCode == ConnectionResult.SUCCESS)
            && (GooglePlayServicesUtil.GOOGLE_PLAY_SERVICES_VERSION_CODE >= versionCode)) {
        return true;
    } else {
        return false;
    }
}

And you can just pass -1 for versionCode parameter.

IgorGanapolsky
  • 26,189
  • 23
  • 116
  • 147
0

2023 updated answer!

if (GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(getApplicationContext()) == ConnectionResult.SUCCESS){
                // available
            }else{
               // unavailable
             
            }
Rezwan
  • 61
  • 2