开发者

How to stop a thread in android which is started using PostDelayed method

开发者 https://www.devze.com 2023-02-19 10:22 出处:网络
I have created a thread in my android application to fetch data by making http request to a server. I have used following code to create thread and defined handler as follows.

I have created a thread in my android application to fetch data by making http request to a server.

I have used following code to create thread and defined handler as follows.

private Handler mHandler = new Handler();
f开发者_C百科inal Runnable mUpdateTimeTask = new Runnable() {
    public void run() {
        dilogShow=false;
        getappdata();
    }
};

And to start this thread i have used following line of code

mHandler.postDelayed(mUpdateTimeTask, 20000);

And to stop it i am using following line of code which works some times, but not always.

mHandler.removeCallbacks(mUpdateTimeTask);

the getappdata() function is as follows:

public void getappdata() {
    final Handler handler = new Handler() {
    @Override
    public void handleMessage(Message message) {
        // managing UI here
        };
    };

    Thread thread = new Thread() {
        @Override
        public void run() {
            // sending http request here
        };
    };  

    thread.start();
}

Please help me.


You can use thread.stop(); Make the thread global so you can use it outside the function also. It stops sometimes when it completes the thread execution otherwise it hangs. the action on thread and not the handler will do the trick. Handler here is just to delay the start of the thread.

0

精彩评论

暂无评论...
验证码 换一张
取 消