我正在使用下面的代码来注册应用令牌:
public class RegistrationIntentService extends IntentService {
private static final String TAG = "RegIntentService";
private static final String[] TOPICS = {"global"};
public static final String TOKEN_ID = "registration_id";
private final static int MAX_ATTEMPTS = 5;
private final static int BACKOFF_MILLI_SECONDS = 2000;
private String token = null;
public RegistrationIntentService() {
super(TAG);
}
@Override
protected void onHandleIntent(Intent intent) {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
try {
synchronized (TAG) {
Random random = new Random();
InstanceID instanceID = InstanceID.getInstance(this);
long backoff = BACKOFF_MILLI_SECONDS + random.nextInt(1000);
for (int i = 1; i <= MAX_ATTEMPTS; i++) {
try {
token = instanceID.getToken(getString(R.string.gcm_defaultSenderId), GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);
sharedPreferences.edit().putBoolean(QuickstartPreferences.SENT_TOKEN_TO_SERVER, true).apply();
} catch (IOException e) {
if (i == MAX_ATTEMPTS) {
break;
}
try {
Thread.sleep(backoff);
} catch (InterruptedException e1) {
break;
}
}
// increase backoff exponentially
backoff *= 2;
}
// further processing for token goes here
}
sendRegistrationToServer(token);
subscribeTopics(token);
} catch (Exception e) {
Log.d(TAG, "Failed to complete token refresh", e);
// sharedPreferences.edit().putBoolean(QuickstartPreferences.SENT_TOKEN_TO_SERVER, false).apply();
}
Intent registrationComplete = new Intent(QuickstartPreferences.REGISTRATION_COMPLETE);
LocalBroadcastManager.getInstance(this).sendBroadcast(registrationComplete);
}
}
但如果设备离线,它不会将令牌注册到应用服务器。当设备连接时,它在应用服务器数据库中没有注册令牌,我无法向它发送推送通知。
如何管理应用程序以在连接时将其令牌发送到应用程序服务器?
我试图添加类似的东西:
try {
token = instanceID.getToken(getString(R.string.gcm_defaultSenderId), GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);
RegisterTOServer(token);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
到主要活动中的 onResume() 方法,但这会使应用程序变得很慢。