[ACCEPTED]-How to start a new Thread in a service?-android

Accepted answer
Score: 43

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

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

Score: 34

Example of new thread creation taken from 3 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 2 the Runnable that contains your Network 1 operations.

Score: 13

You can use HandlerThread and post to it, here 1 is an example to service that has one.

public class NetworkService extends Service {

    private HandlerThread mHandlerThread;
    private Handler mHandler;
    private final IBinder mBinder = new MyLocalBinder();

    @Override
    public void onCreate() {
        super.onCreate();

        mHandlerThread = new HandlerThread("LocalServiceThread");
        mHandlerThread.start();

        mHandler = new Handler(mHandlerThread.getLooper());
    }

    public void postRunnable(Runnable runnable) {
        mHandler.post(runnable);
    }

    public class MyLocalBinder extends Binder {
        public NetworkService getService() {
            return NetworkService.this;
        }
    }

    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }
}
Score: 3

You may define your jobs in a runnable object, use 4 a thread object for running it and start 3 this thread in your service's onStartCommand() function. Here 2 is my notes:

In your service class:

  1. define your main loop in an Runnable object
  2. create Thread object with the runnable object as parameter

In your 1 service class's onStartCommand method():

  1. call thread object's start function()

my code :

private Runnable busyLoop = new Runnable() {
    public void run() {
        int count = 1;
        while(true) {
            count ++;
            try {
                Thread.sleep(100);
            } catch (Exception ex) {
                ;
            }
            ConvertService.running.sendNotification("busyLoop" + count);                      
        }
    }
};

public int onStartCommand(Intent intent, int flags, int startId) {
    sendNotification("onStartCommand");
    if (! t.isAlive()) {
        t.start();
    }
    return START_STICKY;
}

More Related questions