Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to start a new Thread in a service?

Tags:

android

I am developing an Android app and I am doing some heavy work (bringing data from an online web page and parsing it to store in database) in a service. Currently, it is taking about 20+ mins and for this time my UI is stuck. I was thinking of using a thread in service so my UI doesn't get stuck but it is giving error. I am using the following code:

Thread thread = new Thread() {       @Override       public void run() {           try {               while(true) {                   sleep(1000);                   Toast.makeText(getBaseContext(), "Running Thread...", Toast.LENGTH_LONG).show();               }           } catch (InterruptedException e) {            Toast.makeText(getBaseContext(), e.toString(), Toast.LENGTH_LONG).show();           }       }   };  thread.start(); 

This simple code is giving run time error. Even If I take out the while loop, it is still not working. Please, can any one tell me what mistake I am doing. Apparently, I copied this code directly from an e-book. It is suppose to work but its not.

like image 683
U.P Avatar asked Nov 14 '10 17:11

U.P


People also ask

How do I run a service from a different thread?

new Thread(new Runnable() { @Override public void run() { Intent intent=new Intent(getApplicationContext(), SensorService. class); startService(intent); } }). start(); this thread only start the service in different thread but service run in main thread.

Can you start a service from background thread?

You can start a service from an activity or other application component by passing an Intent to startService() or startForegroundService() . The Android system calls the service's onStartCommand() method and passes it the Intent , which specifies which service to start.

On which thread does a service run?

Service runs in the main thread of its hosting process; the service does not create its own thread and does not run in a separate process unless you specify otherwise.


2 Answers

Android commandment: thou shall not interact with UI objects from your own threads

Wrap your Toast Display into runOnUIThread(new Runnable() { });

like image 88
Konstantin Pribluda Avatar answered Sep 30 '22 22:09

Konstantin Pribluda


Example of new thread creation taken from Android samples (android-8\SampleSyncAdapter\src\com\example\android\samplesync\client\NetworkUtilities.java):

public static Thread performOnBackgroundThread(final Runnable runnable) {     final Thread t = new Thread() {         @Override         public void run() {             try {                 runnable.run();             } finally {              }         }     };     t.start();     return t; } 

runnable is the Runnable that contains your Network operations.

like image 23
Zelimir Avatar answered Sep 30 '22 22:09

Zelimir