有没有一种方法可以一次性取消订阅所有主题?
我正在使用Firebase Messaging从一些已订阅的主题接收推送通知,但是我需要一次性取消订阅所有主题而不是一个一个地取消。这可能吗?
有没有一种方法可以一次性取消订阅所有主题?
我正在使用Firebase Messaging从一些已订阅的主题接收推送通知,但是我需要一次性取消订阅所有主题而不是一个一个地取消。这可能吗?
FirebaseInstanceId.getInstance().deleteInstanceId()
(参考:deleteInstanceId()) 并将其包装在 try/catch 语句中以处理潜在的 IOException 异常。这将重置实例 ID,然后您可以使用新实例 ID 和令牌订阅新主题。如果你想避免删除InstanceId,并且避免由于高概率的有缺陷实现而在本地数据库或远程数据库中保存时错过一些已订阅的主题,那么请先获取所有已订阅的主题:
var options = BaseOptions(headers: {'Authorization':'key = YOUR_KEY'});
var dio = Dio(options);
var response = await dio.get('https://iid.googleapis.com/iid/info/' + token,
queryParameters: {'details': true});
Map<String, dynamic> subscribedTopics = response.data['rel']['topics'];
在这里获取您的密钥: Firebase控制台 -> 您的项目 -> 项目设置 -> 云消息传递 -> 服务器密钥
获取您的令牌:
var firebaseMessaging = FirebaseMessaging();
String token;
firebaseMessaging.getToken().then((value) {
token = value;
});
现在请取消订阅所有主题:
Future<void> unsubscribeFromAllTopics() async {
for (var entry in subscribedTopics.entries) {
await Future.delayed(Duration(milliseconds: 100)); // throttle due to 3000 QPS limit
unawaited(firebaseMessaging.unsubscribeFromTopic(entry.key)); // import pedantic for unawaited
debugPrint('Unsubscribed from: ' + entry.key);
}
}
所有代码均使用Dart语言编写。
有关实例ID的更多信息: https://developers.google.com/instance-id/reference/server
final FirebaseMessaging messaging= FirebaseMessaging.getInstance();
FirebaseDatabase.getInstance().getReference().child("topics").addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
String topic = dataSnapshot.getValue(String.class);
messaging.unsubscribeFromTopic(topic);
}...//rest code
在“首选项”中保留一个私人订阅主题列表。
这并不难。以下是我的做法:
public class PushMessagingSubscription {
private static SharedPreferences topics;
public static void init(ApplicationSingleton applicationSingleton) {
topics = applicationSingleton.getSharedPreferences("pushMessagingSubscription", 0);
}
public static void subscribeTopic(String topic) {
if (topics.contains(topic)) return; // Don't re-subscribe
topics.edit().putBoolean(topic, true).apply();
// Go on and subscribe ...
}
public static void unsubscribeAllTopics() {
for (String topic : topics.getAll().keySet()) {
FirebaseMessaging.getInstance().unsubscribeFromTopic(topic);
}
topics.edit().clear().apply();
// FirebaseInstanceId.getInstance().deleteInstanceId();
}
}
针对Java用户:
如果你想按主题分类进行操作,请参考其他答案。如果你想停止接收FCM推送通知,请执行以下操作:
new Thread(new Runnable() {
@Override
public void run() {
try {
FirebaseInstanceId.getInstance().deleteInstanceId();
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
我已将deleteInstanceId()
放置在单独的线程中,以防止java.io.IOException: MAIN_THREAD W/System.err
错误,并用try / catch
包装以处理IOException
异常。
Firebase.messaging.deleteToken()
实际答案为2021年。
如果你正在使用Flutter,如果想要取消订阅所有主题,请使用-
final FirebaseMessaging _fcm = FirebaseMessaging();
_fcm.deleteInstanceID().then((value){
print('deleted all'+value.toString());
});
unsubscribeAllTopics
如下。interface GetTopics {
rel: {topics: {[key: string]: any}}
}
/**
* Unsubcribe all topics except one topic
*
* Example response of `https://iid.googleapis.com/iid/info/${fcmToken}?details=true`
* {
"applicationVersion": "...",
"application": "...",
"scope": "*",
"authorizedEntity": "...",
"rel": {
"topics": {
"TOPIC_KEY_STRING": { // topic key
"addDate": "2020-12-23"
}
}
},
"appSigner": "...",
"platform": "ANDROID"
}
*/
export const unsubcribeAllTopics = async (
fcmTokens: string | string[],
exceptTopic?: string,
) => {
const headers = {
'Content-Type': 'application/json',
Authorization: `key=${process.env.FCM_SERVER_KEY}`,
}
const url = `https://iid.googleapis.com/iid/info/${fcmTokens}?details=true`
try {
const response = await fetch(url, {method: 'GET', headers: headers})
const result: GetTopics = await response.json()
const keys = Object.keys(result.rel.topics)
keys.forEach(key => {
key !== exceptTopic &&
messaging()
.unsubscribeFromTopic(fcmTokens, key)
.catch(error => {
console.error('error', {data: error})
})
})
} catch (error) {
console.error('error', {data: error})
}
}
https://gist.github.com/JeffGuKang/62c280356b5632ccbb6cf146e2bc4b9d
try {
FirebaseInstallations.getInstance().delete()
} catch (e: IOException) {
}
FirebaseInstanceId.getInstance().deleteInstanceId()
。 - Lennon Spirlandelli