2013-02-22 80 views
1

我想在Android上製作一個消息應用程序,我想要GCM。但我無法獲得registrationId。這是我的代碼無法呼叫註冊意圖GCM Android

public static void register(Context context) { 
    //Log.v(TAG,"register"); 
    System.out.println("-----------------------------Authentication Register-----------------------"); 
    Intent registrationIntent = new Intent(
      "com.google.android.c2dm.intent.REGISTER"); 
    // sets the app name in the intent 
    registrationIntent.putExtra("app", 
      PendingIntent.getBroadcast(context, 0, new Intent(), 0)); 
    registrationIntent.putExtra("sender", SENDER_ID); 
    context.startService(registrationIntent); 
} 

public static void unregister(Context context) { 
    Intent unregIntent = new Intent(
      "com.google.android.c2dm.intent.UNREGISTER"); 
    unregIntent.putExtra("app", 
      PendingIntent.getBroadcast(context, 0, new Intent(), 0)); 
    context.startService(unregIntent); 
} 
    } 

我的廣播接收器類

@Override 
public final void onReceive(Context context, Intent intent) { 
    System.out.println("------------------------------------BroadCastReceiver---------------------------------"); 
    MyIntentService.runIntentInService(context, intent); 
    setResult(Activity.RESULT_OK, null, null); 
} 

MyIntentService類

static void runIntentInService(Context context, Intent intent) { 
    System.out.println("--------------------------------Intent---------------------------------"); 
    synchronized (LOCK) { 
     contextC = context; 
     if (sWakeLock == null) { 
      PowerManager pm = (PowerManager) context 
        .getSystemService(Context.POWER_SERVICE); 
      sWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, 
        "my_wakelock"); 
     } 
    } 
    sWakeLock.acquire(); 
    intent.setClassName(context, MyIntentService.class.getName()); 
    context.startService(intent); 
} 

@Override 
public final void onHandleIntent(Intent intent) { 
    try { 
     System.out.println("---------------------------------Register-------------------------------------------"); 
     String action = intent.getAction(); 
     Log.v("Intent", "RegisterIntent"); 
     if (action.equals("com.google.android.c2dm.intent.REGISTRATION")) { 
      Log.v("Intent", "RegisterIntent1"); 
      handleRegistration(intent); 
     } else if (action.equals("com.google.android.c2dm.intent.RECEIVE")) { 
      handleMessage(intent); 
     } else if (action.equals("com.example.gcm.intent.RETRY")) { 
      String token = intent.getStringExtra("token"); 
      // make sure intent was generated by this class, not by a 
      // malicious app 
      if (TOKEN.equals(token)) { 
       SharedPreferences settings = getSharedPreferences(
         PREFS_NAME, 0); 
       String registrationId = settings.getString(
         "registrationId", null);// get from shared 
               // properties 
       if (registrationId != null) { 
        // last operation was attempt to unregister; send 
        // UNREGISTER intent again 
        Authentication.unregister(this); 
       } else { 
        // last operation was attempt to register; send REGISTER 
        // intent again 
        Authentication.register(this); 
       } 
      } 
     } 
    } finally { 
     synchronized (LOCK) { 
      sWakeLock.release(); 
     } 
    } 
} 

private void handleRegistration(Intent intent) { 
    String registrationId = intent.getStringExtra("registration_id"); 
    //Log.v("RegistrationId", registrationId); 
    String error = intent.getStringExtra("error"); 
    String unregistered = intent.getStringExtra("unregistered"); 
    // registration succeeded 
    if (registrationId != null) { 
     SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0); 
     SharedPreferences.Editor editor = settings.edit(); 
     editor.putString("registrationId", registrationId); 
     editor.commit(); 
     //Log.v("Hello", "Registration Idaiudhaodhafhsofahsfs"); 
     // store registration ID on shared preferences 
     // notify 3rd-party server about the registered ID 
    } 

    // unregistration succeeded 
    if (unregistered != null) { 
     // get old registration ID from shared preferences 
     // notify 3rd-party server about the unregistered ID 
    } 

    // last operation (registration or unregistration) returned an error; 
    if (error != null) { 
     if ("SERVICE_NOT_AVAILABLE".equals(error)) { 
      if ("SERVICE_NOT_AVAILABLE".equals(error)) { 
       long backoffTimeMs = 12;// get back-off time from shared 
             // preferences 
       long nextAttempt = SystemClock.elapsedRealtime() 
         + backoffTimeMs; 
       Intent retryIntent = new Intent(
         "com.example.gcm.intent.RETRY"); 
       retryIntent.putExtra("token", TOKEN); 
       PendingIntent retryPendingIntent = PendingIntent 
         .getBroadcast(contextC, 0, retryIntent, 0); 
       AlarmManager am = (AlarmManager) contextC 
         .getSystemService(Context.ALARM_SERVICE); 
       am.set(AlarmManager.ELAPSED_REALTIME, nextAttempt, 
         retryPendingIntent); 
       backoffTimeMs *= 2; // Next retry should wait longer. 
       // update back-off time on shared preferences 
      } else { 
       // Unrecoverable error, log it 
       //Log.i(TAG, "Received error: " + error); 
      } 
      // optionally retry using exponential back-off 
      // (see Advanced Topics) 
     } else { 
      // Unrecoverable error, log it 
      Log.i(TAG, "Received error: " + error); 
     } 
    } 
} 

private void handleMessage(final Intent intent) { 
    // final String ridesJSON=intent.getStringExtra("rides"); 
    // System.out.print(ridesJSON); 
    Handler h = new Handler(Looper.getMainLooper()); 
    //Log.v("Message Chat", intent.getStringExtra("message")); 

    h.post(new Runnable(){ 

     @Override 
     public void run() { 
      // TODO Auto-generated method stub 
      Toast.makeText(contextC, intent.getStringExtra("message"), Toast.LENGTH_SHORT).show(); 
     } 



    }); 
    /* 
    * h.post(new Runnable(){ 
    * 
    * @Override public void run() { // TODO Auto-generated method stub 
    */ 
    // } 

    // }); 
    // server sent 2 key-value pairs, score and time 
    // String score = intent.getStringExtra("score"); 
    // String time = intent.getStringExtra("time"); 
    // generates a system notification to display the score and time 
} 

我的活動課

protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_user_detail); 
    email = (TextView) findViewById(R.id.textEmail); 
    Authentication.register(this); 
} 

@Override 
public boolean onCreateOptionsMenu(Menu menu) { 
    // Inflate the menu; this adds items to the action bar if it is present. 
    getMenuInflater().inflate(R.menu.activity_user_detail, menu); 
    return true; 
} 

public void butSubmitClick(View view) { 
    userDetail = new UserDetail(); 
    userDetail.setId(1); 
    userDetail.setName("Nilesh"); 
    userDetail.setEmail(email.getText() + ""); 
    settings = getSharedPreferences(PREFS_NAME, 0); 
    registrationId = settings.getString("registrationId", null); 
    SharedPreferences.Editor editor = settings.edit(); 
    editor.putString("email", email.getText() + ""); 
    editor.commit(); 
    Log.v("UserDetail ID", registrationId); 
    userDetail.setRegistrationId(registrationId); 
    Intent intent = new Intent(UserDetailActivity.this, MainActivity.class); 
    UserDetailActivity.this.startActivity(intent); 
    new SendUserDetail().execute(userDetail); 
} 

但我總是得到註冊ID爲空。我甚至認爲可能需要一些時間才能註冊。但等待ID並沒有幫助我

請,有人可以幫我

回答

0

我用圖案的文件提出here。很多東西都是由Google圖書館完成的,並且像我一樣開箱即用。這可能對我有幫助。

+0

我已遵循此鏈接http://developer.android.com/google/gcm/gcm.html上的文檔,它具有良好的處理所有情況 – user1827423 2013-02-22 17:18:38

0

也許我錯過了一些東西,但我看不到你真的在哪裏調用GCMRegistrar類?事情是這樣的:

GCMRegistrar.checkDevice(this); 
GCMRegistrar.checkManifest(this); 
final String regId = GCMRegistrar.getRegistrationId(this); 
if (regId.equals("")) { 
    GCMRegistrar.register(this, SENDER_ID); 
} else { 
    Log.v(TAG, "Already registered"); 
} 

另外,我還創建了一個小型的開源項目,這將幫助你辦理註冊ID的處理。或許是有趣的,看看在:https://code.google.com/p/gcmutils/

1

在mainActivity()調用下面的代碼:

GCMRegistrar.register(this, SENDER_ID); 

此行實際上請求您的GCM到您的設備註冊到GCM。 成功註冊後,將調用以下GCMIntentService方法。

@Override protected void onRegistered(Context context, String registrationId) { 
    // here you will get registrationId. 
    // Use this registration id save it safely 
    // as you need to use it after for your message passing. 
}