问题
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