Where to quit the handler thread that used for realm operations in Android?

試著忘記壹切 提交于 2019-12-23 05:34:19

问题


I have an android application that I do many realm operations. I wanted to do those stuff on background and to do that I have used handler threads.

I also used handler threads in some of my activities and service classes and I quit() those handler threads inside ofonTerminate() or onDestroy() methods.

However I do not know where should I quit the handler thread when I use it inside if a non-activity classes since they do not have onDestroy() methods. I have commented the handlerThread.quit() parts because one of them was giving an error. I have many class that has the similar implementation and I have implemented them in the same way. I was thinking closing handler threads after the work is done would make sense however something is wrong with it because I get the error when I uncomment the handlerThread.quit() lines.

    @Override
    public void find(Func1<RealmQuery<PlaylistSchedule>, RealmQuery<PlaylistSchedule>> query,
                     Action1<Result<List<PlaylistSchedule>>> onResult) {
        if (query != null) {
            handlerThread = new HandlerThread("MyHandlerThreadplaylistScheduleDao");

            handlerThread.start();
            looper = handlerThread.getLooper();

            Handler handler = new Handler(looper);

            handler.post(new Runnable(){
                @Override
                public void run() {
                    Timber.log(Log.DEBUG, "PlaylistDaoImpl", "find Thread.currentThread().getName() " + Thread.currentThread().getName());
                    mDatabase.findRealmObject(PlaylistSchedule.class, query,
                            result -> {

                                onResult.call(Result.getData(PlaylistScheduleMapper.copyFromRealm(result.data)));
                                //handlerThread.quit();
                            },

                            err -> {

                                onResult.call(Result.getError(err));
                                //handlerThread.quit();
                            }
                    );
                }
            });


        }

    }

The error that I have faced it is the following:

: Handler (android.os.Handler) {19be0f} sending message to a Handler on a dead thread

Thanks in advance.

来源:https://stackoverflow.com/questions/59416059/where-to-quit-the-handler-thread-that-used-for-realm-operations-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!