我想在每30秒内更新用户位置,而我使用的是射击请求。Bellow中的代码:
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();
}
}
使用firbasejobdispatcher使用JobsChedulerhttps://developer.android.com/topic/performance/scheduling.html
您可以使用融合的位置服务获取位置更新。我创建了一个服务以获取位置更新。此代码将为您提供onLocationChanged
方法中的位置。在这里查看我的答案
尝试以下:
mHandler = new Handler();
Runnable r = new Runnable() {
@override
public void run() {
f();
mHandler.postDelayed(this, 30000);
}
};
mHandler.postDelayed(r, 30000);
您必须在可运行的内部再次调用handler.postDelayed()
方法,因为它仅执行一次,这是正常的行为。像这样将可运行的人分开:
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秒钟称呼它。
尝试一下,它起作用
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();
final Handler ha=new Handler();
Runnable runnable = new Runnable() {
@Override
public void run() {
// ...
ha.postDelayed(this,30000);
}
};
ha.post(runnable);