android 我怎样才能等到所有FCM订阅都完成

vfh0ocws  于 2022-12-25  发布在  Android
关注(0)|答案(1)|浏览(126)

我获取服务器并得到一个包含要订阅主题的数组,我循环它并订阅每个主题,我想做的是等待这个过程完成,然后开始新的活动。
我用循环数做的,如果它等于数组的长度减一,那么开始新的活动。下面是我的代码:

int length = subscribeTo.length();
for (int i = 0; i < length; i++) {
    String sub = null;
    try {
        sub = subscribeTo.get(i).toString();
    } catch (JSONException e) {
        e.printStackTrace();
    }
    int finalI = i;
    JSONObject finalData = data;
    String finalSub = sub;
    FirebaseMessaging.getInstance().subscribeToTopic(sub).addOnCompleteListener(new OnCompleteListener<Void>() {
        @Override
        public void onComplete(@NonNull Task<Void> task) {
            Log.e("sub", finalSub);
            if (!task.isSuccessful()) {
                Toast.makeText(MainActivity.this, "can't login in", Toast.LENGTH_SHORT).show();
                return;
            }
            Log.e("test", "sub" + finalI);
            if (finalI == length - 1) {
                try {
                    editor.putInt("sub_length", length);
                    editor.putString("restaurant_name", finalData.get("restaurant_name").toString());
                    editor.putString("username", finalData.get("username").toString());
                    editor.putString("password", finalData.get("password").toString());
                    editor.putString("sub" + finalI, finalSub);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                Intent intent = new Intent(MainActivity.this, MainActivity2.class);
                startActivity(intent);
                editor.apply();
                finish();
            }
        }

    });
}

没有更好的方法了吗?顺便说一句,我对java还是新手。

pqwbnv8z

pqwbnv8z1#

似乎没有人回应不管是什么,我搜索了很多,这里是我如何解决它使用CountDownLatch
代码:

int length = subscribeTo.length();
CountDownLatch latch = new CountDownLatch(length);

for (int i = 0; i < length; i++) {
    String sub = null;
    try {
        sub = subscribeTo.get(i).toString();
    } catch (JSONException e) {
        e.printStackTrace();
    }
    int finalI = i;
    String finalSub = sub;
    FirebaseMessaging.getInstance().subscribeToTopic(subscribeTo.get(i).toString()).addOnCompleteListener(task -> {
        if (task.isSuccessful()) {
            editor.putString("sub" + finalI, finalSub);
            latch.countDown(); // The number will decrease
        }
    });
}

latch.await(); // Here it will wait until it ensures that all subscriptions are completed
editor.putInt("sub_length", length);
editor.putString("restaurant_name", dataa.get("restaurant_name").toString());
editor.putString("username", dataa.get("username").toString());
editor.putString("password", dataa.get("password").toString());
editor.apply();
Intent intent = new Intent(MainActivity.this, MainActivity2.class);
startActivity(intent);
Log.e("done", "yes");

相关问题