Android   发布时间:2022-04-28  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了android – ScheduledThreadPoolExecutor用于定期任务(使用Retrofit)只需触发一次而不再重复大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我有以下代码用于每隔X秒从服务器轮询未读通知计数

我通过App.onCreate()中的scheduledThreadPoolExecutor启动此过程

Log.d("XXX","requesTing Notification count from server ...");

调用一次(我可以在Logcat中看到),但两个Retrofit回调函数都没有被调用(实际上没有Retrofit调试日志).更重要的是,“从服务器请求通知计数……”永远不会再次打印(即周期性任务没有运行)

我正在使用Retrofit进行其他webservice调用(在用户输入时)并且它们工作正常(我可以在logcat中看到传入和传出的请求/响应)

public class App extends Application  {



    private scheduledexecutorservice scheduleTaskExecutor;
    ...


    @Override
    public void onCreate() {
        super.onCreate();

        //region Set up the perioDic notification count listener task


        scheduleTaskExecutor= Executors.newscheduledThreadPool(2);
        scheduleTaskExecutor.scheduleAtFixedRate(new PerioDicNotifCountFetchTask(),5,TimeUnit.SECONDS);

        //endregion
    }


    class PerioDicNotifCountFetchTask implements Runnable {

        @Override
        public void run() {
            Log.d("XXX","requesTing Notification count from server ...");
            EMRestClient.getmEMRestservice().getNotificationCount(new CallBACk<NotificationCount>() {
                @Override
                public void success(NotificationCount response,Response unused) {

                    int unreadNotifCount = response.getCount();

                    Log.d("XXX","successfully fetched notification count,unread = " + response.getCount());
                    if (unreadNotifCount>0){
                        // call listener to repaint menu
                        for (NewNotificationListener x :notifListeners){
                            x.onNewNotificationReceived(response.getCount());    
                        }
                    }
                }

                @Override
                public void failure(RetrofitError error) {
                    Log.d("XXX","Failed to fetch notification count from server");
                }
            });

        }
    }


}

代码的改进部分在这里

@POST("/notification/notification_count/")
    void getNotificationCount(CallBACk<NotificationCount> callBACk);

解决方法

可能会发生一些异常,因为后续调用将被抑制. ScheduledThreadPoolExecutor only “ticking” once

因此,尝试将您的代码放在runOnUiThread的runnable中,如Scheduling recurring task in Android

大佬总结

以上是大佬教程为你收集整理的android – ScheduledThreadPoolExecutor用于定期任务(使用Retrofit)只需触发一次而不再重复全部内容,希望文章能够帮你解决android – ScheduledThreadPoolExecutor用于定期任务(使用Retrofit)只需触发一次而不再重复所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。