Android: how to run AsyncTask at regular interval in background service

我的未来我决定 提交于 2019-12-25 18:29:55

问题


How do I run an AsyncTask at regular interval of 2 mins sleep for 10 times in the background service?

As VM stops my service at any time, my AsyncTask is also getting closed.

I have tried ScheduledThreadPoolExecutor, Timer, TimerTask all gets stopped once Service gets stopped.

Is there a good option start with?

Any help is appreciated.


回答1:


Your service will never get stopped but you should show notification. Try implementing foreground service. foreground service

Foreground service displays notification and is never stopped.

Implement this code snippet in your service

Notification notification = new Notification(R.drawable.icon, getText(R.string.ticker_text),
        System.currentTimeMillis());
Intent notificationIntent = new Intent(this, ExampleActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
notification.setLatestEventInfo(this, getText(R.string.notification_title),
        getText(R.string.notification_message), pendingIntent);
startForeground(ONGOING_NOTIFICATION_ID, notification);



回答2:


Have you tried the Handler? U can read more about this in this link



来源:https://stackoverflow.com/questions/23601173/android-how-to-run-asynctask-at-regular-interval-in-background-service

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!