谷歌云消息传递:数据库中的重复令牌



我使用谷歌云消息传递来发送通知。我的应用程序将令牌(显然来自谷歌)发送到我的服务器数据库......问题是save token request同时被发送到服务器两次(完全相同,就像克隆一样)!所以,通过服务器我无法解决这个问题(因为时间是一样的,我无法分辨insert if not exist)......通过应用程序我不知道我是否有问题。

我认为问题来自谷歌,但我不知道。

这是我的注册代码:

        GCMRegistrar.checkDevice(this);
        GCMRegistrar.checkManifest(this);
        registerReceiver(mHandleMessageReceiver, new IntentFilter(DISPLAY_MESSAGE_ACTION));
        regId = GCMRegistrar.getRegistrationId(this);
        if (regId.equals("")) {
            new registra_background().execute();
        } else {
            if (!GCMRegistrar.isRegisteredOnServer(this)) {
                mRegisterTask = new AsyncTask<Void, Void, Void>() {
                    @Override
                    protected Void doInBackground(Void... params) {
                        ServerUtilities.register(context, regId);
                        return null;
                    }
                    @Override
                    protected void onPostExecute(Void result) {
                        mRegisterTask = null;
                    }
                };
                mRegisterTask.execute(null, null, null);
            }
        }

这是被调用的类

private class registra_background extends AsyncTask<Void, Integer, Void> {
    int progress_status;
    @Override
    protected void onPreExecute(){
        super.onPreExecute();
    }
    @Override
    protected Void doInBackground(Void... params){
        try{
            if (gcm == null) {
                gcm = GoogleCloudMessaging.getInstance(context);
            }
            regId = gcm.register(SENDER_ID);
            Log.e("TOKEN",regId);
        }catch(Exception ex){
            System.out.println("Errore dati");
        }
        return null;
    }
    @Override
    protected void onProgressUpdate(Integer... values){
    }
    @Override
    protected void onPostExecute(Void result){
        mRegisterTask = new AsyncTask<Void, Void, Void>() {
            @Override
            protected Void doInBackground(Void... params) {
                ServerUtilities.register(context, regId);
                return null;
            }
            @Override
            protected void onPostExecute(Void result) {
                mRegisterTask = null;
            }
        };
        mRegisterTask.execute(null, null, null);
    }
}

这是服务器类

public final class ServerUtilities {
private static final int MAX_ATTEMPTS = 5;
private static final int BACKOFF_MILLI_SECONDS = 2000;
private static final Random random = new Random();
static public void register(final Context context, final String regId) {
    Database db;
    db = new Database(context);
    try {
        db.open();
    } catch (SQLException sqle) {
        throw sqle;
    }
    Cursor variabili=db.variabili();
    int x=1;
    String pvPref="",pvPrefProv="",pvPrefCitta="",pvPrefIndirizzo="";
    while(variabili.moveToNext()){
        if(x==1){
            pvPref=variabili.getString(variabili.getColumnIndex("valore"));
        }else if(x==2){
            pvPrefProv=variabili.getString(variabili.getColumnIndex("valore"));
        }else if(x==3){
            pvPrefCitta=variabili.getString(variabili.getColumnIndex("valore"));
        }else if(x==4){
            pvPrefIndirizzo=variabili.getString(variabili.getColumnIndex("valore"));
        }
        x++;
    }
    String serverUrl = SERVER_URL;
    Map<String, String> params = new HashMap<String, String>();
    params.put("regId", regId);
    params.put("token_push", regId);
    params.put("pvPref", pvPref);
    params.put("device",android.os.Build.MODEL);
    params.put("pvPrefProv", pvPrefProv);
    params.put("pvPrefCitta", pvPrefCitta);
    params.put("pvPrefIndirizzo", pvPrefIndirizzo);
    params.put("app_version", "2.0");
    params.put("os", Build.VERSION.RELEASE);
    long backoff = BACKOFF_MILLI_SECONDS + random.nextInt(1000);
    for (int i = 1; i <= MAX_ATTEMPTS; i++) {
        try {
            post(serverUrl, params);
            SystemClock.sleep(500);
            GCMRegistrar.setRegisteredOnServer(context, true);
            return;
        } catch (IOException e) {
            if (i == MAX_ATTEMPTS) {
                break;
            }
            try {
                Thread.sleep(backoff);
            } catch (InterruptedException e1) {
                Thread.currentThread().interrupt();
                return;
            }
            backoff *= 2;
        }
    }
}
public static void unregister(final Context context, final String regId) {
    String serverUrl = SERVER_URL + "/unregister";
    Map<String, String> params = new HashMap<String, String>();
    params.put("regId", regId);
    try {
        post(serverUrl, params);
        GCMRegistrar.setRegisteredOnServer(context, false);
    } catch (IOException e) {
    }
}
private static void post(String endpoint, Map<String, String> params) throws IOException {
    URL url;
    try {
        url = new URL(endpoint);
    } catch (MalformedURLException e) {
        throw new IllegalArgumentException("invalid url: " + endpoint);
    }
    StringBuilder bodyBuilder = new StringBuilder();
    Iterator<Entry<String, String>> iterator = params.entrySet().iterator();
    while (iterator.hasNext()) {
        Entry<String, String> param = iterator.next();
        bodyBuilder.append(param.getKey()).append('=').append(param.getValue());
        if (iterator.hasNext()) {
            bodyBuilder.append('&');
        }
    }
    String body = bodyBuilder.toString();
    byte[] bytes = body.getBytes();
    HttpURLConnection conn = null;
    try {
        conn = (HttpURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setUseCaches(false);
        conn.setFixedLengthStreamingMode(bytes.length);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded;charset=UTF-8");
        OutputStream out = conn.getOutputStream();
        out.write(bytes);
        out.close();
        int status = conn.getResponseCode();
        if (status != 200) {
            throw new IOException("Errore " + status);
        }
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }
}
}

您的代码将新的注册方法(GoogleCloudMessaging.register)与旧的已弃用的GCMRegistr类混合在一起。两个异步任务的嵌套用法非常混乱。

如果您在服务器上收到两个具有相同注册 ID 的请求,则您的客户端代码是唯一负责的。与其尝试调试这个过于复杂的代码,我建议你使用当前的Google GCM演示作为参考。

当您

检查时

 if(regId==""){
        //here simply put
 GCMRegistrar.register(this, SENDER_ID);
 }else{
 ServerUtilities.register(context, regId);
   }

休息你应该只在服务器实用程序中注意

有关更多信息,请查看 Apidemo 中提供的 GCMDemo

上面的代码只会点击一次注册服务

快乐的克里斯马斯

相关内容

最新更新