2015-03-02 57 views
-1

我試圖使用GoogleAuthUtil.getToken生成一個令牌,我可以使用它來獲取通知密鑰。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): [email protected] 
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

也發佈你的日誌。 – Psypher 2015-03-02 13:33:55

+0

我解決了問題,我必須爲我的android應用程序創建兩個客戶端ID,第二個爲我的應用程序 – 2015-03-03 17:28:23

+0

您可以發佈您的答案,以便將來可以幫助某人。 – Psypher 2015-03-04 20:07:37

回答

0

我發現了我的問題的解決方案。 :)

我終於弄清楚,我只用客戶端ID爲Web應用程序, 據谷歌文檔

*

生成客戶端上的通知鍵: 打開您在Google Developers Console中的項目。 單擊APIS & AUTH>憑證。 在OAuth下,單擊創建新的客戶端ID。 在「創建客戶端ID」對話框中,選擇「Web應用程序」作爲應用程序類型,然後單擊「創建客戶端ID」。 從Web應用程序的客戶端ID>客戶端ID複製值。此客戶端ID都代表一個谷歌帳戶

*

而且我錯過了這是客戶端ID爲Android應用程序。爲了產生新的,請按照下列步驟一件重要的事情。

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 

Basicaly android應用程序的客戶端ID,允許您的應用程序向谷歌服務器發出請求。