I want to create a service, that runs a method after 10 seconds over and over again, until I stop it, even if the app is closed. My attempted code is below
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);
}
The program just stops running immediately; how can I change my code to get the desired behaviour?
create a broadcast receiver that will start your service after receiving broadcast from
AlarmManager
:start your broadcast receiver for the first time when you start your application:
Also add this to your Manifest File:
You should also have alook at this START_STICKY if you want your service to be started by Android system as soon as resources are available instead of receiving Broadcast by AlarmManager.