2013-02-22 5 views
1

Я пытаюсь создать приложение для обмена сообщениями на Android, и я хочу использовать GCM. Но я не могу получить регистрацию. Это мой кодНе удалось назвать регистрацию Intent 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); 
} 
    } 

Мои BroadcastReceiver Класс

@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); 
} 

Но я всегда получаю регистрационный номер нулевой. Я даже подумал, что может потребоваться некоторое время, чтобы зарегистрироваться. Но ждет ид не помогли мне

Пожалуйста, может кто-то помочь мне

ответ

0

Я использовал шаблон предложил here в документации. Google делает много вещей, и это работает для меня как из коробки. Это может мне помочь.

+0

Я следил за документацией по этой ссылке http://developer.android.com/google/gcm/gcm.html, которая имеет хорошую обработку всех случаев – user1827423

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"); 
} 

Кроме того, я создал небольшой проект с открытым исходным кодом, который поможет вам с обработкой обращения регистрационного идентификатора. Может быть может быть интересно, проверить его на: 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. 
} 
Смежные вопросы