适用于GooglePlayServicesUtil Android的NoClassDefFoundError

时间:2013-10-21 13:26:00

标签: android google-cloud-messaging

我正在尝试实施Google Cloud Messaging。当我运行应用程序时,它会抛出异常

10-21 18:46:14.991: E/AndroidRuntime(4817): FATAL EXCEPTION: main
10-21 18:46:14.991: E/AndroidRuntime(4817): java.lang.NoClassDefFoundError: com.google.android.gms.common.GooglePlayServicesUtil
10-21 18:46:14.991: E/AndroidRuntime(4817):     at com.corporate.test.HomePage.checkPlayServices(HomePage.java:211)
10-21 18:46:14.991: E/AndroidRuntime(4817):     at com.corporate.test.HomePage.onCreate(HomePage.java:140)
10-21 18:46:14.991: E/AndroidRuntime(4817):     at android.app.Activity.performCreate(Activity.java:5020)
10-21 18:46:14.991: E/AndroidRuntime(4817):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
10-21 18:46:14.991: E/AndroidRuntime(4817):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2148)
10-21 18:46:14.991: E/AndroidRuntime(4817):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2211)
10-21 18:46:14.991: E/AndroidRuntime(4817):     at android.app.ActivityThread.access$600(ActivityThread.java:149)
10-21 18:46:14.991: E/AndroidRuntime(4817):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1300)
10-21 18:46:14.991: E/AndroidRuntime(4817):     at android.os.Handler.dispatchMessage(Handler.java:99)
10-21 18:46:14.991: E/AndroidRuntime(4817):     at android.os.Looper.loop(Looper.java:153)
10-21 18:46:14.991: E/AndroidRuntime(4817):     at android.app.ActivityThread.main(ActivityThread.java:4987)
10-21 18:46:14.991: E/AndroidRuntime(4817):     at java.lang.reflect.Method.invokeNative(Native Method)
10-21 18:46:14.991: E/AndroidRuntime(4817):     at java.lang.reflect.Method.invoke(Method.java:511)
10-21 18:46:14.991: E/AndroidRuntime(4817):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:821)
10-21 18:46:14.991: E/AndroidRuntime(4817):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:584)
10-21 18:46:14.991: E/AndroidRuntime(4817):     at dalvik.system.NativeStart.main(Native Method)

我的活动代码是

import java.io.IOException;
import java.util.concurrent.atomic.AtomicInteger;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.gcm.GoogleCloudMessaging;
import com.nextra.utils.AppState;

public class HomePage extends Activity {
    RelativeLayout mytrips_relative, approval_relative,
            view_transations_relative;
    Button backViewTransations, continueViewTransactions;
    ImageView logout;
    final Context context = this;
    public String TAG = "HomePage";
    boolean isConnected;
    /*
     * GCM Client Variables
     * */
    public static final String EXTRA_MESSAGE = "message";
    public static final String PROPERTY_REG_ID = "registration_id";
    private static final String PROPERTY_APP_VERSION = "appVersion";
    private static final int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;

    String SENDER_ID = "XXXX";
    TextView mDisplay;
    GoogleCloudMessaging gcm;
    AtomicInteger msgId = new AtomicInteger();
    Context contextGCM;

    String regid;

    @SuppressLint("NewApi")

    /*
     * GCM Client Variables END
     * */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_home_page);



        /*
         * GCM PlayServices On
         * */
        contextGCM = getApplicationContext();

        // Check device for Play Services APK. If check succeeds, proceed with
        // GCM registration.
        if (checkPlayServices()) {
            gcm = GoogleCloudMessaging.getInstance(this);
            regid = getRegistrationId(contextGCM);
            Log.d("Registration id ", regid + "");
            if (regid.isEmpty()) {
                registerInBackground();
            }
        } else {
            Log.i(TAG, "No valid Google Play Services APK found.");
        }
    }





    @Override
    protected void onResume() {
        super.onResume();
        // Check device for Play Services APK.
        checkPlayServices();
    }

    /**
     * Check the device to make sure it has the Google Play Services APK. If it
     * doesn't, display a dialog that allows users to download the APK from the
     * Google Play Store or enable it in the device's system settings.
     */
    private boolean checkPlayServices() {
        int resultCode = GooglePlayServicesUtil
                .isGooglePlayServicesAvailable(this);
        if (resultCode != ConnectionResult.SUCCESS) {
            if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
                GooglePlayServicesUtil.getErrorDialog(resultCode, this,
                        PLAY_SERVICES_RESOLUTION_REQUEST).show();
            } else {
                Log.i(TAG, "This device is not supported.");
                finish();
            }
            return false;
        }
        return true;
    }

    /**
     * Stores the registration ID and the app versionCode in the application's
     * {@code SharedPreferences}.
     * 
     * @param context
     *            application's context.
     * @param regId
     *            registration ID
     */
    private void storeRegistrationId(Context context, String regId) {
        final SharedPreferences prefs = getGcmPreferences(context);
        int appVersion = getAppVersion(context);
        Log.i(TAG, "Saving regId on app version " + appVersion);
        SharedPreferences.Editor editor = prefs.edit();
        editor.putString(PROPERTY_REG_ID, regId);
        editor.putInt(PROPERTY_APP_VERSION, appVersion);
        editor.commit();
    }

    /**
     * Gets the current registration ID for application on GCM service, if there
     * is one.
     * <p>
     * If result is empty, the app needs to register.
     * 
     * @return registration ID, or empty string if there is no existing
     *         registration ID.
     */
    @SuppressLint("NewApi")
    private String getRegistrationId(Context context) {
        final SharedPreferences prefs = getGcmPreferences(context);
        String registrationId = prefs.getString(PROPERTY_REG_ID, "");
        if (registrationId.isEmpty()) {
            Log.i(TAG, "Registration not found.");
            return "";
        }
        // Check if app was updated; if so, it must clear the registration ID
        // since the existing regID is not guaranteed to work with the new
        // app version.
        int registeredVersion = prefs.getInt(PROPERTY_APP_VERSION,
                Integer.MIN_VALUE);
        int currentVersion = getAppVersion(context);
        if (registeredVersion != currentVersion) {
            Log.i(TAG, "App version changed.");
            return "";
        }
        return registrationId;
    }

    /**
     * Registers the application with GCM servers asynchronously.
     * <p>
     * Stores the registration ID and the app versionCode in the application's
     * shared preferences.
     */
    private void registerInBackground() {
        new AsyncTask<Void, Void, String>() {
            @Override
            protected String doInBackground(Void... params) {
                String msg = "";
                try {
                    if (gcm == null) {
                        gcm = GoogleCloudMessaging.getInstance(contextGCM);
                    }
                    regid = gcm.register(SENDER_ID);
                    Log.d("registration Id", regid + "");
                    msg = "Device registered, registration ID=" + regid;

                    // You should send the registration ID to your server over
                    // HTTP, so it
                    // can use GCM/HTTP or CCS to send messages to your app.
                    sendRegistrationIdToBackend();

                    // For this demo: we don't need to send it because the
                    // device will send
                    // upstream messages to a server that echo back the message
                    // using the
                    // 'from' address in the message.

                    // Persist the regID - no need to register again.
                    storeRegistrationId(contextGCM, regid);
                } catch (IOException ex) {
                    msg = "Error :" + ex.getMessage();
                    // If there is an error, don't just keep trying to register.
                    // Require the user to click a button again, or perform
                    // exponential back-off.
                }
                return msg;
            }

            @Override
            protected void onPostExecute(String msg) {
                mDisplay.append(msg + "\n");
            }
        }.execute(null, null, null);
    }



    @Override
    protected void onDestroy() {
        super.onDestroy();
    }




}

看到我已经安装了Google Play Services并且还完成了构建路径我仍然收到错误。

4 个答案:

答案 0 :(得分:1)

我在Android Studio 0.3.1下遇到了同样的错误。在build.gradle文件中,我添加了#34; play-services&#34; (v3.2.0或更高版本)获得:

dependencies {
    compile 'com.android.support:support-v4:18.0.0'
    compile 'com.google.android.gms:play-services:3.2.+'
}

我必须在最终工作之前重启Android Studio。使用工具&gt; Android&gt; SDKManager确保Google Play&#34; extras&#34;安装。

答案 1 :(得分:1)

我尝试了所有可以找到的建议,至少重新创建了两次图书馆项目。

然后Eclipse内存不足,很有趣,因为我有64 GB的RAM。

我决定重新启动Windows。当一切都恢复时,它只是起作用。 :-P

答案 2 :(得分:0)

检查您是否已导入Google Play服务项目,并将其添加为项目的依赖库。转到导入的项目属性 - &gt; Android部分并选中“Is Library”框

然后在项目依赖项时添加它。如果您正在使用Eclipse,请转到您的项目属性 - &gt; Android部分和图书馆部分,添加导入的Google Play服务项目。

此外,修复项目属性和清理也可以帮助您。尝试右键单击项目 - &gt; Android工具 - &gt;修复项目属性。然后,清除您的项目并尝试运行您的项目。

答案 3 :(得分:-2)

当在运行时未找到代码的类时会发生此错误。通常这意味着包装和/或部署代码时出现问题。检查IDE的设置,尝试重建整个项目。