Android 检查是否可用正确的 Google Play 服务:“不幸的是,应用程序已停止工作”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22493465/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 06:04:07  来源:igfitidea点击:

Check if correct Google Play Service available: "Unfortunately application has stopped working"

android

提问by user3144836

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.

每次我在手机上运行它时,应用程序都会崩溃。有什么不对?它说不幸的是“appname”已停止工作。我还尝试了其他方法来检查 googleplay 服务,但它总是崩溃。我更新了我的 google play 服务,并且有一个可以正常工作的 google map v2。此代码的任何解决方案?它在我运行 android 4.1.2 的手机和我的 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;
    }
}

采纳答案by user3144836

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

谢谢你们的回应。我刚刚从我的 LogCat 中弄清楚了。我必须将它包含在我的 Android 清单中。

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

回答by Dhaval Patel

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

要检查是否GooglePlayServices可用,请使用GoogleApiAvailability. isGooglePlayServicesAvailable(),作为GooglePlayServicesUtil已弃用isGooglePlayServicesAvailable()

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.

更新:检查 google play 服务是否可用,如果 google play 服务不可用且错误可恢复,则打开对话框以解决错误。

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

回答by Renetik

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

回答by Pedro Varela

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.

将此方法添加到您的启动画面;如果您没有更新或安装 Google Play 服务,您的应用将根本无法启动。

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

回答by Pong Petrung

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

您在谷歌服务的新 2016谷歌示例的阅读文档中设置更改 checkPlayServices

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

回答by Shayden117

Change

改变

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

to

int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getApplicationContext();

回答by IgorGanapolsky

You can check for Play Services presence like this:

您可以像这样检查 Play 服务是否存在:

/**
 * 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 -1for versionCodeparameter.

你可以只通过-1versionCode参数。

回答by Simon Bengtsson

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.

据我所知,这是在应用程序启动时在启动画面(如活动)中检查 Google Play 服务所需的最少代码。类似于 Dhavel 的回答,但没有不必要的代码。

You can verify it works for all cases by simply passing a custom result code to the getErrorDialogmethod. 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.

您可以通过简单地将自定义结果代码传递给getErrorDialog方法来验证它适用于所有情况。此处列出所有结果代码。使用 onResume 很重要,因为在 Google Play 等更新 Google Play 服务后返回应用程序后会调用它。

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) {
            val dialog = availability.getErrorDialog(this, resultCode, 0)
            dialog.show()
            return false
        }
        return true
    }

}