保证只有一个timerTasks与服务中的线程

时间:2015-12-01 12:07:27

标签: android android-service timertask

我的Android应用程序有一项服务,将在定时器任务中以指定的间隔创建。该任务应该通过异步任务检出webservice,如果启用了Internet,则发送一些信息,否则它应该等待(例如,5秒)并再次检查连接。

我的问题是:如何在timertask等待时阻止创建任务?

我希望在任何时候只有一项任务正在运作。

我的代码:

mTimer.scheduleAtFixedRate(new MyTask(), 0, 10000); //creating tasks in service

class MyTask extends TimerTask {

@Override
public void run() {
    if (!isLocked) {
        new Thread(new Runnable() {@Override
            public void run() {
                isLocked = true;
                if (!isInternet) {
                    do {
                        Log.v("TestService", "Waiting...");
                        SystemClock.sleep(5000);
                        isInternet = getInternetConn();
                    } while (!isInternet);
                } else {
                    //do work
                }
                isLocked = false;
            }).run();
        }
    }
}

1 个答案:

答案 0 :(得分:0)

我建议您按照此过程进行操作,我用它来获取GCM_Registration ID,就像您可以使用它一样检查您的互联网连接。

的作用类似于:onStartCommand()mServiceHandler.sendMessage(msg);启动一个asynctask检查我们有GCM-ID如果是,我们停止服务,如果没有,那么我们再次通过asynctask检查GCM-ID

package com.urbanft.utils;

import java.io.IOException;

import android.app.Service;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.os.Process;
import android.text.TextUtils;

import com.google.android.gms.gcm.GoogleCloudMessaging;
import com.urbanft.app.GlobalPreference;

public class GCMIdFetchService extends Service {

    private final String SENDER_ID = "916449540455";
    private Looper mServiceLooper;
    private ServiceHandler mServiceHandler;
    private static final long INTERVAL = 1000;
    private GoogleCloudMessaging mGoogleCloudMessaging;
    private String mRegisterationId;    

    private final class ServiceHandler extends Handler {
        public ServiceHandler(Looper looper) {
            super(looper);
        }

        @Override
        public void handleMessage(Message msg){
            new GCMIdFetchSearviceTask().execute("");
        }
    }

    protected void initialization() {
        mGoogleCloudMessaging = GoogleCloudMessaging.getInstance(getApplicationContext());
    }

    @Override
    public void onCreate() {
        HandlerThread thread = new HandlerThread("ServiceStartArguments",Process.THREAD_PRIORITY_BACKGROUND);
        thread.start();
        mServiceLooper = thread.getLooper();
        mServiceHandler = new ServiceHandler(mServiceLooper);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Message msg = mServiceHandler.obtainMessage();
        msg.arg1 = startId;
        mServiceHandler.sendMessage(msg);
        return START_NOT_STICKY;
    }

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

    @Override
    public void onDestroy() {
    }

    class GCMIdFetchSearviceTask extends AsyncTask<String, String, String>{

        @Override
        protected String doInBackground(String... params) {
            getGCMID();
            return null;
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);

            String gcmId = GlobalPreference.getInstance(getApplicationContext()).getGCMRegistrationId();
            if(!TextUtils.isEmpty(gcmId)){
                stopSelf();
                return;
            }
            new Handler().postDelayed(new Runnable() {
                public void run() {
                    Message msg = mServiceHandler.obtainMessage();
                    mServiceHandler.sendMessage(msg);
                }
            }, INTERVAL);
        }
    }

    private void getGCMID() {
        try{
            if(mGoogleCloudMessaging == null){
                mGoogleCloudMessaging = GoogleCloudMessaging.getInstance(getApplicationContext());
            }
            mRegisterationId = mGoogleCloudMessaging.register(SENDER_ID);
            GlobalPreference.getInstance(getApplicationContext()).setGCMRegistrationId(mRegisterationId);
        }
        catch (IOException err){
            err.printStackTrace();
        }
    }
}