我正在尝试在我的应用程序中每2分钟执行一次任务,在我阅读了一些实现方法后,我选择使用ScheduledExecutorService,但我可以让它更新UI。我做错了什么?
以下是代码:
public class ScheduledTask {
private final String TAG="ScheduledTask";
private final ScheduledExecutorService scheduler =
Executors.newScheduledThreadPool(1);
private Context context;
private Activity activity;
public ScheduledTask(Context c, Activity a)
{
this.context=c;
this.activity=a;
}
public void RefreshMapPeriodically()
{
final ScheduledFuture refreshHandle =
scheduler.scheduleAtFixedRate(new Runnable()
{
public void run()
{
//iau din baza de date sqlLite locala semnele apropiate de locatia mea
NotificationAdministration notify=new NotificationAdministration(context);
final ArrayList<SpeedRestriction> lista=notify.getNotificationFromLocalArea(MainActivity.CURRENT_LOCATION.getLatitude(), MainActivity.CURRENT_LOCATION.getLongitude());
Log.i(TAG,"Run! Preluare din db");
if(activity !=null)
{
// If you need update UI, simply do this:
((Activity)context).runOnUiThread(new Runnable() {
public void run()
{
//le adaug pe harta
UpdateLocalMap.setSpeedMarkers(lista,MainActivity.getGoogleMap() , MainActivity.getMarkere());
}
});
}
}
}, 0, 1, MINUTES);
scheduler.schedule(new Runnable() {
public void run()
{
refreshHandle.cancel(true);
}
}, 60 * 60 * 2, SECONDS);
}
我从MainActivity中调用它
ScheduledTask doRefresh=new ScheduledTask(context,this);
doRefresh.RefreshMapPeriodically();