Android - 如何在运行服务时停止启动服务间隔?

时间:2017-11-29 06:35:51

标签: android service

我有一个名为myService的服务类,我使用interval来运行服务

这里是代码:

public class myService extends Service {
    public Runnable mRunnable = null;
    IBinder mBinder = new LocalBinder();

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

    public class LocalBinder extends Binder {
        public myService getServerInstance() {
            return myService.this;
        }
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        final Handler mHandler = new Handler();
        mRunnable = new Runnable() {
            @Override
            public void run() {
                Log.d("Service jalan", "beneran dah");
                DatabaseHandler db = new DatabaseHandler(getApplicationContext());
                List<Contact> contacts = db.getAllContacts();
                for (Contact cn : contacts)
                {
                    int idsql = cn.getID();
                    if(String.valueOf(cn.getFlag()).equals("0")){
                        Log.d("Id", String.valueOf(cn.getID()) + " Flag :" + cn.getFlag());
                        sending a  = new sending(); //communicate to server
                        a.execute();
                    }
                    else
                    {
                        Log.d("Data kosong", "atau tidak ada flag = 0");
                    }
                }
                mHandler.postDelayed(mRunnable, 30 * 1000);
            }
        };
        mHandler.postDelayed(mRunnable, 30 * 1000);
        return super.onStartCommand(intent, flags, startId);
    }
}

问题:

当我的服务仍在if statement上运行但间隔已经循环30秒时,我的服务将重新开始,

我该如何避免?

1 个答案:

答案 0 :(得分:0)

您可以使用标志在重新启动服务之前检查服务是否正在进行中,如

 boolean isInProgress = false;
 mRunnable = new Runnable() {
            @Override
            public void run() {
                Log.d("Service jalan", "beneran dah");
                if(!isInProgress){
                isInProgress = true;
                DatabaseHandler db = new DatabaseHandler(getApplicationContext());
                List<Contact> contacts = db.getAllContacts();
                for (Contact cn : contacts)
                {
                    int idsql = cn.getID();
                    if(String.valueOf(cn.getFlag()).equals("0")){
                        Log.d("Id", String.valueOf(cn.getID()) + " Flag :" + cn.getFlag());
                        sending a  = new sending(); //communicate to server
                        a.execute();
                    }
                    else
                    {
                        Log.d("Data kosong", "atau tidak ada flag = 0");
                    }
                  }
                 isInProgress = false;
               }
                mHandler.postDelayed(mRunnable, 30 * 1000);
            }