每30秒呼叫方法不起作用

时间:2017-04-25 06:31:33

标签: android service

我想每隔30秒更新一次用户位置,我正在使用服务的截击请求。 下面的代码:

public class CarLocationUpdateService extends Service {


    Context context;
    long delay = 1000; // delay for 1 sec.
    long period = 10000; // repeat every 10 sec.

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

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        context = this;


        Handler ha=new Handler();
        ha.postDelayed(new Runnable() {
            @Override
            public void run() {

                //call function

                CarLocationUpdateVolleyClass carLocationUpdateVolleyClass=new CarLocationUpdateVolleyClass(context);
                carLocationUpdateVolleyClass.carLocationRequest();

            }
        }, delay);



        return START_STICKY;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }
}

6 个答案:

答案 0 :(得分:0)

将jobScheduler与firbaseJobDispatcher一起使用 https://developer.android.com/topic/performance/scheduling.html

答案 1 :(得分:0)

您可以使用融合位置服务来获取位置更新。我已创建了一项服务来获取位置更新。此代码将以onLocationChanged方法为您提供位置。 在这里查看我的答案here

答案 2 :(得分:0)

试试这个:

mHandler = new Handler();
    Runnable r = new Runnable() {
        @override 
        public void run() {
            f();
            mHandler.postDelayed(this, 30000);
        }
    };
    mHandler.postDelayed(r, 30000);

答案 3 :(得分:0)

   final Handler ha=new Handler();
    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            // ...

            ha.postDelayed(this,30000);
        }
    };
    ha.post(runnable);

答案 4 :(得分:0)

你必须在runnable中再次调用handler.postDelayed()方法,因为它只执行一次,这是一种正常的行为。从处理程序中分离runnable,如下所示:

Handler ha = new Handler();

private Runnable yourRunnable = new Runnable() {

    @Override
    public void run() {

  CarLocationUpdateVolleyClass carLocationUpdateVolleyClass=new CarLocationUpdateVolleyClass(context);
                carLocationUpdateVolleyClass.carLocationRequest();
     ha.postDelayed(yourRunnable, 30000);
    }
};

ha.post(yourRunnable);
顺便说一句,你的问题告诉我们一些关于30秒的事情,但你只需要每10秒调用一次。

答案 5 :(得分:0)

试试这个有效

public void doWork(){
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                // This method will be executed once the timer is over
                // insert your data to db here


                // close this activity
               doWork();
                Toast.makeText(MainActivity.this, "LOL", Toast.LENGTH_SHORT).show();
            }
        }, TIME_OUT);
    }

然后在onStartCommand()

中简单地调用此方法
doWork();
相关问题