Android – scheduledthreadpoolexecutor is used for periodic tasks (using retrofit) that only need to be triggered once and will not be repeated

I have the following code to poll the unread notification count from the server every x seconds

I start this process through the scheduledthreadpoolexecutor in app. Oncreate()

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

It is called once (I can see it in logcat), but neither of the two retrofit callback functions is called (actually there is no retrofit debugging log). More importantly, "request notification count from server..." will never be printed again (that is, the periodic task is not running)

I am using retrofit to make other WebService calls (at user input) and they are working properly (I can see incoming and outgoing requests / responses in 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(), 0, 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");
                }
            });

        }
    }


}

The improved part of the code is here:

    @POST("/notification/notification_count/")
    void getNotificationCount(Callback<NotificationCount> callback);

resolvent:

Some exceptions may occur because subsequent calls will be suppressed. Scheduledthreadpoolexecutor only "ticking" once

Therefore, try to put your code in the runnable of runonuithread, such as scheduling recursive task in Android

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>