我注意到每次我将我的应用程序部署到我的手机时,它都会在解析中复制安装以接收推送通知。每当我重新安装应用程序时,如何避免这种情况发生?
最佳答案
经过一周的研究和试错,我终于找到了可行的解决方案。基本上,您需要做两件事来实现这一目标:
- 在您的 Android 应用中:在初始化和保存
ParseInstallation
时传递一些唯一 ID。我们将使用 ANDROID_ID . - 在 Parse Cloud Code 中:在保存新的
Installation
之前,检查它的唯一 ID 是否存在于旧的Installation
中。如果是,请删除旧的。
怎么做:
在应用程序的
onCreate()
方法中://First: get the ANDROID_ID String android_id = Settings.Secure.getString(this.getContentResolver(), Settings.Secure.ANDROID_ID); Parse.initialize(this, "APP_ID", "CLIENT_KEY"); //Now: add ANDROID_ID value to your Installation before saving. ParseInstallation.getCurrentInstallation().put("androidId", android_id); ParseInstallation.getCurrentInstallation().saveInBackground();
在您的云代码中,添加以下内容:
Parse.Cloud.beforeSave(Parse.Installation, function(request, response) { Parse.Cloud.useMasterKey(); var androidId = request.object.get("androidId"); if (androidId == null || androidId == "") { console.warn("No androidId found, save and exit"); response.success(); } var query = new Parse.Query(Parse.Installation); query.equalTo("androidId", androidId); query.addAscending("createdAt"); query.find().then(function(results) { for (var i = 0; i < results.length; ++i) { console.warn("iterating over Installations with androidId= "+ androidId); if (results[i].get("installationId") != request.object.get("installationId")) { console.warn("Installation["+i+"] and the request have different installationId values. Try to delete. [installationId:" + results[i].get("installationId") + "]"); results[i].destroy().then(function() { console.warn("Installation["+i+"] has been deleted"); }, function() { console.warn("Error: Installation["+i+"] could not be deleted"); }); } else { console.warn("Installation["+i+"] and the request has the same installationId value. Ignore. [installationId:" + results[i].get("installationId") + "]"); } } console.warn("Finished iterating over Installations. A new Installation will be saved now..."); response.success(); }, function(error) { response.error("Error: Can't query for Installation objects."); }); });
就是这样!
您可能想知道的事情:
- Android 设备没有完美的唯一标识符。就我而言,我使用了 ANDROID_ID .你可能会用别的东西。 Read this official article以获得更好的照片。
- 请注意,在第一次调用
put("androidId", android_id);
后,一个名为androidId
的新列将添加到您的Installation
Parse 应用仪表板中的 TableView 。
关于android - 如何使用 Parse 避免安装重复?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28050986/