How to run code in background thread on Android?

I want some code to work in the background all the time. I do not want to do this in the service. Is there any other possible way?

I tried to call the Thread class in my Activity but my Activity stays in the background for a while and then stops. The Thread class also stops working.

 class testThread implements Runnable { @Override public void run() { File file = new File( Environment.getExternalStorageDirectory(), "/BPCLTracker/gpsdata.txt" ); int i = 0; RandomAccessFile in = null; try { in = new RandomAccessFile( file, "rw" ); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } //String line =null; while ( true ) { HttpEntity entity = null; try { if ( isInternetOn() ) { while ( ( line = in.readLine() ) != null ) { HttpClient client = new DefaultHttpClient(); String url = "some url"; HttpPost request = new HttpPost( url ); StringEntity se = new StringEntity( line ); se.setContentEncoding( "UTF-8" ); se.setContentEncoding( new BasicHeader( HTTP.CONTENT_TYPE, "application/json" ) ); entity = se; request.setEntity( entity ); HttpResponse response = client.execute( request ); entity = response.getEntity(); i++; } if ( ( line = in.readLine() ) == null && entity != null ) { file.delete(); testThread t = new testThread(); Thread t1 = new Thread( t ); t1.start(); } } else { Thread.sleep( 60000 ); } // end of else } catch (NullPointerException e1) { e1.printStackTrace(); } catch (InterruptedException e2) { e2.printStackTrace(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } }// end of while }// end of run } 
+97
android multithreading
Mar 18 '13 at 8:24
source share
6 answers

If you need:

  • execute code on background thread

  • execute code that SHOULD NOT touch / update the user interface

  • execute a (short) code that takes no more than a few seconds to complete

THEN use the following clean and efficient template that uses AsyncTask:

 AsyncTask.execute(new Runnable() { @Override public void run() { //TODO your background code } }); 
+316
Jul 21 '15 at 21:03
source share

Remember that “Background Launch”, “Continuous Launch” are two different tasks.

For long-term background processes, threads are not optimal with Android. However, here is the code and do it at your own peril and risk ...

Remember that the service or thread will run in the background, but our task is to execute the trigger (call again and again) to receive updates, i.e. after completing the task, we need to call the function for the next update.

Timer (periodic trigger), Alarm (time base trigger), Broadcast (event base trigger), recursion will awaken our functions.

 public static boolean isRecursionEnable = true; void runInBackground() { if (!isRecursionEnable) // Handle not to start multiple parallel threads return; // isRecursionEnable = false; when u want to stop // on exception on thread make it true again 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() { // update UI runInBackground(); } }); } else { runInBackground(); } } }).start(); } 

Using the service: if you start the service, it will start, it will complete the task and itself will stop working. after completing the task. termination can also be caused by an exception, or the user killed him manually from the settings. START_STICKY (Sticky Service) is an option provided by Android, in which the service restarts itself if the service is terminated.

Remember the question of the difference between multiprocessing and multithreading? A service is a background process (just like an action without a user interface), just like you start a thread in an action to avoid loading the main thread (activity thread), just like you need to run threads (or asynchronous tasks) in service to avoid service load.

In one expression, if you want to start a background continuation task, you need to start StickyService and start the thread in the event-based service.

+37
Mar 18 '13 at 8:41
source share

I want some code to run in the background continuously. I do not want to do this in the service. Is there another way?

Most likely, the mechanism you are looking for is AsyncTask . It is directly intended to execute a background process in a background thread. In addition, its main advantage is that it offers several methods that run in the Main (UI) thread and allow you to update your user interface if you want to inform the user about some progress in the task or update the interface with data received from the background process .

If you do not know how to start here, this is a good tutorial:

Note: It is also possible to use IntentService with ResultReceiver , which also works.

+18
Mar 18 '13 at 8:37
source share

An alternative to AsyncTask is robospice. https://github.com/octo-online/robospice .

Some of the features of robospice.

1. performs asynchronous (in the background AndroidService) network requests (for example: REST requests using Spring Android) .notify you app, in the user interface thread, when the result is ready.

2. Strongly typed! You make your queries using POJO and you get POJO as query results.

3. There are no restrictions on the POJOs that were used for the requests, nor on the activity classes that you use in your projects.

4. shows the results (in Json with both Jackson and Gson, or Xml, or with flat text files, or with binary files, even using ORM Lite).

5.notify your actions (or any other context) of the result of a network request, if and only if they are still alive

6.no memory leak in general, like Android bootloaders, unlike Android AsyncTasks notifies you of your actions in their user interface thread.

7. Uses a simple but robust exception handling model.

Samples for a start. https://github.com/octo-online/RoboSpice-samples .

Robospice sample at https://play.google.com/store/apps/details?id=com.octo.android.robospice.motivations&feature=search_result .

+2
Mar 18 '13 at 8:44
source share
 class Background implements Runnable { private CountDownLatch latch = new CountDownLatch(1); private Handler handler; Background() { Thread thread = new Thread(this); thread.start(); try { latch.await(); } catch (InterruptedException e) { /// e.printStackTrace(); } } @Override public void run() { Looper.prepare(); handler = new Handler(); latch.countDown(); Looper.loop(); } public Handler getHandler() { return handler; } } 
+1
Mar 03 '18 at 17:05
source share

If you need to start a thread with different codes, here is an example:

Listener:

 public interface ESLThreadListener { public List onBackground(); public void onPostExecute(List list); } 

Stream class

 public class ESLThread extends AsyncTask<Void, Void, List> { private ESLThreadListener mListener; public ESLThread() { if(mListener != null){ mListener.onBackground(); } } @Override protected List doInBackground(Void... params) { if(mListener != null){ List list = mListener.onBackground(); return list; } return null; } @Override protected void onPostExecute(List t) { if(mListener != null){ if ( t != null) { mListener.onPostExecute(t); } } } public void setListener(ESLThreadListener mListener){ this.mListener = mListener; } } 

Run different codes:

  ESLThread thread = new ESLThread(); thread.setListener(new ESLThreadListener() { @Override public List onBackground() { List<EntityShoppingListItems> data = RoomDB.getDatabase(context).sliDAO().getSL(fId); return data; } @Override public void onPostExecute(List t) { List<EntityShoppingListItems> data = (List<EntityShoppingListItems>)t; adapter.setList(data); } }); thread.execute(); 
0
Jun 11 '19 at 9:40
source share



All Articles