Start service once and forever untill it gets killed

A simple question, how to make a Service repeat at log cat console msg "hello", as long as the Service is living/is active? I've tried:

@Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.v("LocalService", "Received start id " + startId + ": " + intent);
        Mano lopas = new Mano(this);
        lopas.Lopas();
        while(true) {
        Log.v("HAHA", "hello");
        }
        // We want this service to continue running until it is explicitly
        // stopped, so return sticky.
        return START_STICKY;
    }

But it never returns START_STICKY, actually it doesnt even build the project. I think im missing something about services? I start my service, in MainActivity in my application, like:

startService(new Intent(getApplicationContext(),Myclass.class));

And it runs only once without my while loop in my service. It says me something in Logcat and this is it. Morever, my service starts so many times as many times I re-open my application. How to make service start run once and "forever", I mean untill it gets killed by the system or user kills it.

Answers


First of all, do not forget to register the Service in your Manifest.

This can be done by using

<service android:enabled="true" android:name=".services.Paycan" />

Next is, that your Service (if its not an intentservice) run in the MainUI. If you create an endless loop make sure it's in a background thread, otherwise it will freeze the app.

You can do it using an Asynctask, a Thread which get created with onStartCommand and stopped in onDestroy or use an IntentService instead of a Service.

example:

public class yourTestClass extends Service {

    Thread testThread;
    boolean threadRunning = false;

    @Override
    public void onCreate() {
        super.onCreate(); 
        testThread = new Thread() {
         @Override
         public void run() {
          try {
            while(threadRunning) {
                Thread.sleep(1000);
                Log.i("test", "....");
            }
          } catch (InterruptedException e) {
            e.printStackTrace();
          }
       } 
     };
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
       threadRunning = true;
       testThread.start();
       return START_STICKY;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        threadRunning = false;
    }

Services don't have their own thread, they run on the UI thread. If you want it to run in parallel, you need to create a Thread. So here you should create a Thread in your onStartCommand, and that thread should do whatever it is you want.


Same way you'd log something at intervals in your activity: use a Handler. Post a task that logs a message and re-posts itself to the same Handler using postDelayed(...). Cancel any pending execution in your activity's onPause() or your service's onDestroy().

Note that there is almost never a good reason to explicitly create a Thread or use J2SE constructs like TimerTask in Android. For heavyweight tasks, use AsyncTask. For lightweight tasks, use Handlers. In your case, creating a new Thread would be a ridiculously heavyweight solution for what you want to do.


Need Your Help

Rewrite a sub doman with sitemap.xml file in url to folder with sitemap.xml file

regex apache .htaccess mod-rewrite

Which rewriterule I should write?I have a lot of sitemap.xml files placed in folders separately one by one

is it possible in symfony 1.4 to pass options to the embedded i18n forms?

forms symfony1 internationalization doctrine

I have a Template model which is i18n and has a TemplateForm and a TemplateTranslationForm. I embed the translation form with:

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.