GoogleAuthUtil.getToken - 无值[空指针异常]

时间:2015-03-02 13:28:07

标签: java android google-cloud-messaging google-authentication

我正在尝试使用GoogleAuthUtil.getToken生成可用于获取通知密钥的令牌。

但是,我运行我的应用程序,它崩溃了。

PS:我已经添加了

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

到清单文件

这是我的java代码

package com.javapapers.android;

import java.io.IOException;

import android.accounts.Account;
import android.accounts.AccountManager;
import android.app.Activity;
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.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.google.android.gms.auth.GoogleAuthException;
import com.google.android.gms.auth.GoogleAuthUtil;
import com.google.android.gms.auth.UserRecoverableAuthException;
import com.google.android.gms.gcm.GoogleCloudMessaging;
import com.javapapers.main.MainActivity;

public class RegisterActivity extends Activity {

    Button btnGCMRegister;
    Button btnAppShare;
    GoogleCloudMessaging gcm;
    Context context;
    String regId;

    public static final String REG_ID = "regId";
    private static final String APP_VERSION = "appVersion";

    static final String TAG = "Register Activity";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);

        context = getApplicationContext();

        String accountName = getAccount();

        Log.d("Vitee",accountName);



        final String scope = "audience:server:client_id:"
                + "733298165997-m3pidihedvapju4q43dk1fmc4u13vm3a.apps.googleusercontent.com";
        String id_token = null;

            try {
                id_token = GoogleAuthUtil.getToken(context , accountName ,scope);
            } catch (UserRecoverableAuthException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (GoogleAuthException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }


        Log.d("au_token",id_token);


        // Initialize the scope using the client ID you got from the Console.



        btnGCMRegister = (Button) findViewById(R.id.btnGCMRegister);
        btnGCMRegister.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                if (TextUtils.isEmpty(regId)) {
                    regId = registerGCM();
                    Log.d("RegisterActivity", "GCM RegId: " + regId);
                } else {
                    Toast.makeText(getApplicationContext(),
                            "Already Registered with GCM Server!",
                            Toast.LENGTH_LONG).show();
                }
            }
        });

        btnAppShare = (Button) findViewById(R.id.btnAppShare);
        btnAppShare.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                if (TextUtils.isEmpty(regId)) {
                    Toast.makeText(getApplicationContext(), "RegId is empty!",
                            Toast.LENGTH_LONG).show();
                } else {
                    Intent i = new Intent(getApplicationContext(),
                            MainActivity.class);
                    i.putExtra("regId", regId);
                    Log.d("RegisterActivity",
                            "onClick of Share: Before starting main activity.");
                    startActivity(i);
                    finish();
                    Log.d("RegisterActivity", "onClick of Share: After finish.");
                }
            }
        });


    }

    public String getAccount() {

        Account[] accounts = AccountManager.get(this).
            getAccountsByType("com.google");
        if (accounts.length == 0) {
            return null;
        }
        return accounts[0].name;
    }


    public String registerGCM() {

        gcm = GoogleCloudMessaging.getInstance(this);
        regId = getRegistrationId(context);

        if (TextUtils.isEmpty(regId)) {

            registerInBackground();

            Log.d("RegisterActivity",
                    "registerGCM - successfully registered with GCM server - regId: "
                            + regId);
        } else {
            Toast.makeText(getApplicationContext(),
                    "RegId already available. RegId: " + regId,
                    Toast.LENGTH_LONG).show();
        }
        return regId;
    }

    private String getRegistrationId(Context context) {
        final SharedPreferences prefs = getSharedPreferences(
                MainActivity.class.getSimpleName(), Context.MODE_PRIVATE);
        String registrationId = prefs.getString(REG_ID, "");
        if (registrationId.isEmpty()) {
            Log.i(TAG, "Registration not found.");
            return "";
        }
        int registeredVersion = prefs.getInt(APP_VERSION, Integer.MIN_VALUE);
        int currentVersion = getAppVersion(context);
        if (registeredVersion != currentVersion) {
            Log.i(TAG, "App version changed.");
            return "";
        }
        return registrationId;
    }

    private static int getAppVersion(Context context) {
        try {
            PackageInfo packageInfo = context.getPackageManager()
                    .getPackageInfo(context.getPackageName(), 0);
            return packageInfo.versionCode;
        } catch (NameNotFoundException e) {
            Log.d("RegisterActivity",
                    "I never expected this! Going down, going down!" + e);
            throw new RuntimeException(e);
        }
    }

    private void registerInBackground() {
        new AsyncTask<Void, Void, String>() {
            @Override
            protected String doInBackground(Void... params) {
                String msg = "";
                try {
                    if (gcm == null) {
                        gcm = GoogleCloudMessaging.getInstance(context);
                    }
                    regId = gcm.register(Config.GOOGLE_PROJECT_ID);
                    Log.d("RegisterActivity", "registerInBackground - regId: "
                            + regId);
                    msg = "Device registered, registration ID=" + regId;

                    storeRegistrationId(context, regId);
                } catch (IOException ex) {
                    msg = "Error :" + ex.getMessage();
                    Log.d("RegisterActivity", "Error: " + msg);
                }
                Log.d("RegisterActivity", "AsyncTask completed: " + msg);
                return msg;
            }

            @Override
            protected void onPostExecute(String msg) {
                Toast.makeText(getApplicationContext(),
                        "Registered with GCM Server." + msg, Toast.LENGTH_LONG)
                        .show();
            }
        }.execute(null, null, null);
    }

    private void storeRegistrationId(Context context, String regId) {
        final SharedPreferences prefs = getSharedPreferences(
                MainActivity.class.getSimpleName(), Context.MODE_PRIVATE);
        int appVersion = getAppVersion(context);
        Log.i(TAG, "Saving regId on app version " + appVersion);
        SharedPreferences.Editor editor = prefs.edit();
        editor.putString(REG_ID, regId);
        editor.putInt(APP_VERSION, appVersion);
        editor.commit();
    }
}

这是我的日志文件

03-03 07:23:11.246: D/dalvikvm(22527): GC_FOR_ALLOC freed <1K, 11% free 10531K/11764K, paused 14ms, total 14ms
03-03 07:23:11.311: D/Vitee(22527): i.bensirhir@gmail.com
03-03 07:23:11.336: D/AndroidRuntime(22527): Shutting down VM
03-03 07:23:11.336: W/dalvikvm(22527): threadid=1: thread exiting with uncaught exception (group=0x419fc700)
03-03 07:23:11.351: E/AndroidRuntime(22527): FATAL EXCEPTION: main
03-03 07:23:11.351: E/AndroidRuntime(22527): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.javapapers.android/com.javapapers.android.RegisterActivity}: java.lang.IllegalStateException: Calling this from your main thread can lead to deadlock
03-03 07:23:11.351: E/AndroidRuntime(22527):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2295)
03-03 07:23:11.351: E/AndroidRuntime(22527):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2349)
03-03 07:23:11.351: E/AndroidRuntime(22527):    at android.app.ActivityThread.access$700(ActivityThread.java:159)
03-03 07:23:11.351: E/AndroidRuntime(22527):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1316)
03-03 07:23:11.351: E/AndroidRuntime(22527):    at android.os.Handler.dispatchMessage(Handler.java:99)
03-03 07:23:11.351: E/AndroidRuntime(22527):    at android.os.Looper.loop(Looper.java:176)
03-03 07:23:11.351: E/AndroidRuntime(22527):    at android.app.ActivityThread.main(ActivityThread.java:5419)
03-03 07:23:11.351: E/AndroidRuntime(22527):    at java.lang.reflect.Method.invokeNative(Native Method)
03-03 07:23:11.351: E/AndroidRuntime(22527):    at java.lang.reflect.Method.invoke(Method.java:525)
03-03 07:23:11.351: E/AndroidRuntime(22527):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1046)
03-03 07:23:11.351: E/AndroidRuntime(22527):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:862)
03-03 07:23:11.351: E/AndroidRuntime(22527):    at dalvik.system.NativeStart.main(Native Method)
03-03 07:23:11.351: E/AndroidRuntime(22527): Caused by: java.lang.IllegalStateException: Calling this from your main thread can lead to deadlock
03-03 07:23:11.351: E/AndroidRuntime(22527):    at com.google.android.gms.internal.jx.aV(Unknown Source)
03-03 07:23:11.351: E/AndroidRuntime(22527):    at com.google.android.gms.auth.GoogleAuthUtil.getToken(Unknown Source)
03-03 07:23:11.351: E/AndroidRuntime(22527):    at com.google.android.gms.auth.GoogleAuthUtil.getToken(Unknown Source)
03-03 07:23:11.351: E/AndroidRuntime(22527):    at com.javapapers.android.RegisterActivity.onCreate(RegisterActivity.java:58)
03-03 07:23:11.351: E/AndroidRuntime(22527):    at android.app.Activity.performCreate(Activity.java:5372)
03-03 07:23:11.351: E/AndroidRuntime(22527):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1104)
03-03 07:23:11.351: E/AndroidRuntime(22527):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2257)

1 个答案:

答案 0 :(得分:0)

我找到了解决问题的方法。 :)

我终于认为我只使用 Web应用程序的客户端ID , 根据谷歌文档

*

  

要在客户端上生成通知密钥:       在Google Developers Console中打开您的项目。       点击APIS&amp; AUTH&gt;证书。       在OAuth下,单击“创建新客户端ID”。       在Create Client ID对话框中,选择Web Application作为应用程序类型,然后单击Create Client ID。       从Web应用程序的客户端ID复制值&gt;客户ID。此客户ID表示Google帐户

*

我错过了一个重要的东西,即Android应用程序的客户端ID。为了生成新的,请按照以下步骤操作。

1- Open your project in the Google Developers Console.
2- Click APIS & AUTH > Credentials.
3-  Under OAuth, click Create new Client ID.
4- In the Create Client ID dialog, select installed Application
5- Choose Android 
6 - get the SHA1 KEY from Eclipse as well as the name of your main package. copy and paste values 

基本上是Android应用的客户端ID,允许您的应用向Google服务器发出请求。