這是一個GCM ID問題。嘗試使用Thread.sleep並重試多次,直到收到GCM ID。
int noOfAttemptsAllowed = 5; // Number of Retries allowed
int noOfAttempts = 0; // Number of tries done
bool stopFetching = false; // Flag to denote if it has to be retried or not
String regId = "";
while (!stopFetching)
{
noOfAttempts ++;
GCMRegistrar.register(getApplicationContext(), "XXXX_SOME_KEY_XXXX");
try
{
// Leave some time here for the register to be
// registered before going to the next line
Thread.sleep(2000); // Set this timing based on trial.
} catch (InterruptedException e) {
e.printStackTrace();
}
try
{
// Get the registration ID
regId = GCMRegistrar.getRegistrationId(LoginActivity.this);
} catch (Exception e) {}
if (!regId.isEmpty() || noOfAttempts > noOfAttemptsAllowed)
{
// If registration ID obtained or No Of tries exceeded, stop fetching
stopFetching = true;
}
if (!regId.isEmpty())
{
// If registration ID Obtained, save to shared preferences
saveRegIDToSharedPreferences();
}
}
Thread.sleep代碼和noOfAttemptsAllowed可以根據您的設計和其他參數來發揮各地。我們有一個7000的睡眠時間,以便第一次嘗試登記的概率更高。但是,如果失敗,下一次嘗試將耗用7000毫秒。這可能會導致用戶認爲你的應用程序很慢。所以,用這兩個價值智能地玩耍。
謝謝,我會試試 – LastElb 2015-02-18 11:30:30