关于intentService

由于Service本身不会启动一个单独进程,也不是一条新的线程,所以如果要在service里面进行耗时任务的话,就要开启一个新的线程

 

class NormalService extends Service
    {

        @Override
        public void onCreate() {
            super.onCreate();
            new Thread(new Runnable() {
                @Override
                public void run() {

                }
            }).start();
        }

        @Nullable
        @Override
        public IBinder onBind(Intent intent) {
            return null;
        }
    }

然而还不够,当所有请求处理完后,还需要调用stopSelf方法停止Service后台继续运行。

 

使用intentService便可以解决上述问题:1.回创建独立的worker线程来处理请求。2.会自动停止。3.只需要重写onHandleIntent方法

 

public class MyIntentService extends IntentService {
    public static final String TAG="vczx";
    /**
     * Creates an IntentService.  Invoked by your subclass's constructor.
     *
     * @param name Used to name the worker thread, important only for debugging.
     */
    public MyIntentService() {
        super("MyIntentService");
    }

    @Override
    protected void onHandleIntent(Intent intent) {

        long endTime=System.currentTimeMillis()+20*1000;
        Log.d(TAG, "IntentService Started");
        while(System.currentTimeMillis()<endTime)
        {
            synchronized (this)
            {
                try {
                    wait(endTime-System.currentTimeMillis());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
        Log.d(TAG, "耗时任务完成");
    }
}

 

posted @ 2016-03-21 16:40  巧克力曲奇  阅读(91)  评论(0)    收藏  举报