每次我在手机上运行应用程序时都会崩溃。有什么不对?它说不幸的是“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;
}
}
最佳答案
要检查GooglePlayServices
是否可用,请使用 GoogleApiAvailability
。 isGooglePlayServicesAvailable()
,与 GooglePlayServicesUtil
相同。 isGooglePlayServicesAvailable()
不推荐使用的。
public boolean isGooglePlayServicesAvailable(Context context){
GoogleApiAvailability googleApiAvailability = GoogleApiAvailability.getInstance();
int resultCode = googleApiAvailability.isGooglePlayServicesAvailable(context);
return resultCode == ConnectionResult.SUCCESS;
}
更新:检查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;
}