您应该使用以下代码以确保仅在未注册到服务器时才将 RegId 注册到服务器。
public void GCMWebService(final String regId) {
if (regId.equals("")) {
Log.i(TAG,
"================Inside if in regId=null GCMWebService==============================");
// Automatically registers application on startup.
GCMRegistrar.register(mContext, GCMIntentService.SENDER_ID);
// GCMRegistrar.unregister(this);
} else {
Log.i(TAG,
"================Inside else in regId=null GCMWebService==============================");
// Device is already registered on GCM, needs to check if it is
// registered on our server as well.
if (GCMRegistrar.isRegisteredOnServer(this)) {
// Skips registration.
Log.i(TAG,
"================Inside else in regId=null Already register on Server GCMWebService=============================");
// mDisplay.append(getString(R.string.already_registered) +
// "\n");
} else {
Log.i(TAG,
"================Inside else in regId=null trying to register on Server GCMWebService=============================");
// Try to register again, but not in the UI thread.
// It's also necessary to cancel the thread onDestroy(),
// hence the use of AsyncTask instead of a raw thread.
final Context context = this;
mRegisterTask = new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... params) {
Log.i(TAG,
"================Inside doInBackground Method GCMWebService==============================");
registerToServer(regId);
Log.i(TAG,
"================Server side REegistered or not?"
+ registered);
// At this point all attempts to register with the app
// server failed, so we need to unregister the device
// from GCM - the app will try to register again when
// it is restarted. Note that GCM will send an
// unregistered callback upon completion, but
// GCMIntentService.onUnregistered() will ignore it.
if (!registered) {
Log.i(TAG,
"================Inside unregister inside Do in backgroound GCMWebService==============================");
GCMRegistrar.unregister(context);
}
return null;
}
@Override
protected void onPostExecute(Void result) {
Log.i(TAG,
"================Inside onPostExecute Method GCMWebService==============================");
mRegisterTask = null;
if (!registered) {
/*
* final Toast tag = Toast .makeText( context,
* "Please Check Your Internet Connection and Try again \nOr\nWebservice is not Working now..."
* , Toast.LENGTH_SHORT);
*/
new CountDownTimer(8000, 1000) {
public void onTick(long millisUntilFinished) {
Toast.makeText(
context,
"Please Check Your Internet Connection and Try again \nOr\nWebservice is not Working now...",
Toast.LENGTH_SHORT).show();
}
public void onFinish() {
}
}.start();
}
}
};
mRegisterTask.execute(null, null, null);
}
}
}
希望它会有所帮助。