简体   繁体   中英

How can i create a Thread that running on background on Android

I have a Thread with open socket connection in a activity, I like to use the thread globaly so that I can get data from thread in other Activities. Somethink like running on the background...

Does anyone have a solution or examples for me?

Thank u.

You are looking for Service

or try this code

void runInBackground() {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    // DO your work here
                    // get the data
                    if (activity_is_not_in_background) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                //uddate UI
                            }
                        });
                    }
                    runInBackground();
                }
            });
        }

And the third method using Async Task-- Understanding AsyncTask

If you want multiple activities to have access to this thread then I would combine Vaibs_cool's sample of running a thread (it's just a normal Thread, nothing Android specific about it) and then...

extend Application (make an entry for it in the Manifest) and put that Thread in there.

That way all your activities can talk to it.

You have two options:

If you want to open socket and make it opened even after Activity close use Service

On other hand if you want to open socket during Activity is running and close on Activity close then use AsyncTask

You can find example how to use AsyncTask here

From Docs:

Network operations can involve unpredictable delays. To prevent this from causing a poor user experience, always perform network operations on a separate thread from the UI. The AsyncTask class provides one of the simplest ways to fire off a new task from the UI thread.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM