Demet
Demet

Reputation: 61

Android Thread in Service

I need to write thread in service . But I'm not sure how to do this exactly. There must be more than one thread. Can you help me please.

Upvotes: 0

Views: 2149

Answers (3)

schwertfisch
schwertfisch

Reputation: 4579

This way works great.

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;

public class Servicio extends Service {

    @Override
    public void onCreate() {
        super.onCreate();
        initialize();
    }
    @Override
    public IBinder onBind(Intent arg0) {
        // TODO Auto-generated method stub
        return null;
    }
    public void initialize(){
        Thread th = new Thread(new Runnable() {

            @Override
            public void run() {
                //Your code ......

            }
        });
        th.start();
    }

}

Upvotes: 1

DeeV
DeeV

Reputation: 36045

You start a thread in a service the same way you start a thread in anything. Either use Java threads, timers, or async task.

Java threads are usually started like so:

private Thread yourThread;
private NewRunnable yourRunnable;

@Override
public int onStartCommand(Intent intent, int flags, int startId)
{
   ... code...
   yourThread = new Thread(yourRunnable);
   ... code...
}

private final class NewRunnable extends Runnable
{
   @Override
   public void run()
   {
     ... Code here will be run in new thread....
   }
}

Upvotes: 1

ngesh
ngesh

Reputation: 13501

Just get The context in the Service and Use AsyncTask to create another Thread... Or you can also do

new Thrad(){
public void Run(){
//your implementation..
}
}

Upvotes: 0

Related Questions