gpt4 book ai didi

android - GCM 注册 SERVICE_NOT_AVAILABLE

转载 作者:塔克拉玛干 更新时间:2023-11-02 07:56:32 25 4
gpt4 key购买 nike

这让我很生气。我有一个使用 GCM 的应用程序。我有人提示他们由于错误而无法登录。让我向您展示我是如何进行登录的:

// Login Activity
//....
public void onClickLoginButton (View v) {

// Do some stuff...

new GCMRegister().execute(); //AsyncTask
}

private class GCMRegister extends AsyncTask<Void, Void, Integer> {

@Override
protected Integer doInBackground (Void... params) {
ConnectivityManager connMgr = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();

if (networkInfo != null && networkInfo.isConnected()) {
try {
//Get GCM Registration key
registrationId = googleCloud.register(Settings.PROJECT_NUMBER);
} catch (Exception e) {
Log.e("GCMRegister", e.toString());
return -1;
}
return 1;
} else {
return -3;
}
}

@Override
protected void onPostExecute(Integer result) {
if (result == 1) {
new LoginAsync().execute(); // Another AsyncTask to check in my database if user is valid and save its key
} else {
user.setEnabled(true);
password.setEnabled(true);
login.setEnabled(true);
if (result == -1) {
Toast.makeText(Login.this, "A problem occured login in", Toast.LENGTH_LONG).show();
} else if (result == -3) {
Toast.makeText(Login.this, "I need an internet connection", Toast.LENGTH_LONG).show();
}
}
}

所以很多人提示他们无法登录,因为“登录时出现问题”错误,这表明 GCM 注册失败。即使是我自己的设备,Android 4.4.2,一开始也做不到。我需要尝试登录 2 或 3 次,直到成功(并且我的网络连接良好)。我的 LogCat 上的错误是:

08-04 21:29:10.922: E/GCMRegister(18182): java.io.IOException: SERVICE_NOT_AVAILABLE

那么我的代码有什么问题呢?这让我抓狂。

最佳答案

我们遇到了同样的问题,用户第一次无法登录,但在第 2 次或第 3 次后可以登录,无论网络速度如何。

我们通过使用 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.sleepnoOfAttemptsAllowed 可以根据您的设计和其他参数进行调整。我们的 sleep 时间为 7000,因此第一次尝试注册的概率更高。但是,如果失败,下一次尝试将再消耗 7000 毫秒。这可能会导致用户认为您的应用运行缓慢。因此,请明智地使用这两个值。

关于android - GCM 注册 SERVICE_NOT_AVAILABLE,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25129611/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com