Here's a semi-different way to keep the service forever. There are ways to kill it in code if you wish
Background Service:
package com.ex.ample; import android.app.Service; import android.content.*; import android.os.*; import android.widget.Toast; public class BackgroundService extends Service { public Context context = this; public Handler handler = null; public static Runnable runnable = null; @Override public IBinder onBind(Intent intent) { return null; } @Override public void onCreate() { Toast.makeText(this, "Service created!", Toast.LENGTH_LONG).show(); handler = new Handler(); runnable = new Runnable() { public void run() { Toast.makeText(context, "Service is still running", Toast.LENGTH_LONG).show(); handler.postDelayed(runnable, 10000); } }; handler.postDelayed(runnable, 15000); } @Override public void onDestroy() {
Here's how you start it with your core business or wherever you want:
startService(new Intent(this, BackgroundService.class));
onDestroy() is called when the application closes or gets killed, but runnable just starts it back. You also need to remove the handler callbacks.
Hope this helps someone.
The reason some people do this is because of corporate applications, in which in some cases users / employees cannot stop certain things :)
http://i.imgur.com/1vCnYJW.png
Pierre
source share