1

我正在尝试在 Android 上制作一个消息传递应用程序,我想要 GCM。但我无法获得registrationId。这是我的代码

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 并没有帮助我

拜托,有人可以帮我吗

4

3 回答 3

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.
}
于 2013-02-25T14:10:03.340 回答
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/

于 2013-02-23T10:17:58.250 回答
0

我在文档中使用了此处提出的模式。谷歌图书馆做了很多事情,它对我来说就像开箱即用一样。它可能对你有帮助。

于 2013-02-22T16:46:51.353 回答