bsv
bsv

Reputation: 49

handler, runnable and services: I put everything together and it doesn't really work

I wanted to create a service, that runs a method after 10 seconds over and over again, until I stop it. It doesn't work. Can somebody help me?

package com.example.tauben;


import java.util.Timer;
import java.util.TimerTask;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;

public class Reminder extends Service {


@Override
public IBinder onBind(Intent arg0) {
    return null;
}
@Override
public void onCreate() {
    TimerTask task = new TimerTask() {
        public void run(){
            f();
        }
    };
    Timer timer = new Timer();
    timer.scheduleAtFixedRate(task, 0, 10000);
}
public void f(){
    Toast t = Toast.makeText(this, "Service is still running", Toast.LENGTH_SHORT);
    t.show();
}

}

And this is how I start the service.

    @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Log.d(Log_TAG,"_____________RESTART__________");

    Intent i= new Intent(this, Reminder.class);
    startService(i); 
}

Upvotes: 1

Views: 2674

Answers (2)

d3m0li5h3r
d3m0li5h3r

Reputation: 1967

Well I can think of 2 alternatives to what you are trying to achieve here.

1- Use TimerTask in set a repeating task that will call call the required method every 10 seconds.

2- Use setRepeating method of AlarmManager.

Both these alternatives are way better. You can google search the examples of both to get a better understanding.

Happy Coding :)

Edit:- I seem to got your original code working using Handler's postDelayed()

package com.example.tauben;


import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.widget.Toast;

public class Reminder extends Service {

Handler mHandler;

@Override
public IBinder onBind(Intent arg0) {
    return null;
}
@Override
public void onCreate() {
    mHandler = new Handler();
    Runnable r = new Runnable() {
        @override 
        public void run() {
            f();
            mHandler.postDelayed(this, 10000);
        }
    };
    mHandler.postDelayed(r, 10000);
}
public void f(){
    Toast t = Toast.makeText(this, "Service is still running", Toast.LENGTH_SHORT);
    t.show();
}

}

Upvotes: 1

Diego Palomar
Diego Palomar

Reputation: 7061

What you have to do is bind to service and declare a method where service clients can stop the service. Inside that method you have to call handler.removeCallbacksAndMessages(null) to cancel all runable tasks.

Upvotes: 0

Related Questions