Я звоню обслуживание каждые три минуты, используя следующую функцию:Android сервиса останавливается без вызова OnDestroy
public void RunBackgroundService() {
final Handler service_handler = new Handler();
Timer timer = new Timer();
TimerTask doAsynchronousTask = new TimerTask() {
@Override
public void run() {
service_handler.post(new Runnable() {
public void run() {
context.startService(new Intent(context,BackgroundService.class));
}
});
}
};
timer.schedule(doAsynchronousTask, 0, 180 * 1000);
}
И это моя служба, в которой я запускать уведомление:
public class BackgroundService extends Service {
Helper helper;
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
//Toast.makeText(this, "Service created!", Toast.LENGTH_LONG).show();
}
@Override
public void onDestroy() {
//Toast.makeText(this, "Service stopped", Toast.LENGTH_LONG).show();
}
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
@Override
public void onStart(Intent intent, int startid)
{
helper=new Helper(this);
// Log.d("Service started at:", helper.getdatetime());
Intent n_intent = new Intent(this, MainActivity.class);
PendingIntent pIntent = PendingIntent.getActivity(this, 0, n_intent, 0);
// build notification
// the addAction re-use the same intent to keep the example short
long[] vibrate = { 0, 100, 200, 300 };
Notification n = new Notification.Builder(this)
.setContentTitle("Application")
.setContentText("This is a test")
.setSmallIcon(R.drawable.notification_icon)
.setContentIntent(pIntent)
.setDefaults(Notification.DEFAULT_SOUND)
.setVibrate(vibrate)
.setAutoCancel(true)
.build();
NotificationManager notificationManager =
(NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notificationManager.notify(0, n);
}
}
Очень важно, чтобы я оставался сервисом, работающим в любое время, когда приложение завершает работу службы. Как я могу предотвратить остановку службы?
Что такое 'Помощник'? Кроме того, служба просто публикует уведомление и ничего не делает, пока в конце концов не умрет от скуки. И это происходит каждые три минуты. Если вам нужно периодически запускать задачу, зайдите в https://github.com/evernote/android-job. –