开发者

Android Thread in Service

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


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....
   }
}


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();
    }

}


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..
}
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜