根据友盟的官方文档,如果我们想要获取设备的Device Token,应该这么做:
String device_token = UmengRegistrar.getRegistrationId(context)
说明:
Device Token为友盟生成的用于标识设备的id,长度为44位,不能定制和修改。同一台设备上每个应用对应的Device Token不一样。
获取Device Token的代码需要放在mPushAgent.enable();
后面,注册成功以后调用才能获得Device Token。
如果返回值为空, 说明设备还没有注册成功, 需要等待几秒钟,同时请确保测试手机网络畅通。
但在实际中,我们发现第一次进入应用,在主函数中注册并调用该方法获取到的DeviceToken为空,因此,我写了一个定时来获取DeviceToke:
//获取DeviceToken
if (deviceToken.isEmpty()) {
timer.schedule(new TimerTask() {
@Override
public void run() {
if (deviceToken.isEmpty() && count < 10) {
String temp = UmengRegistrar.getRegistrationId(AtMain.this);
if (temp == null || temp.isEmpty()) {
count++;
} else {
deviceToken = temp;
count = 0;
}
} else {
count = 0;
cancel();
LogUtil.d("debug", "task has cancle and deviceToken=" + deviceToken);
}
}
}, 0, 800);
}
这样一来,我们在后面用到DeviceToken时就能保证不为空了。