Akarsh M
Akarsh M

Reputation: 1611

Keep alive Service in background?

For a demo I print a Toast after Evert 10 sec. using Service class.

It works fine, I'm getting the Toast after every 10 sec if I am on the Activity when I leave the app, Service is not giving the o/p.

But I want to that toast either I'll kill the App or back press Here is code snippet :

ServiceDemo.java

public class ServiceDemo extends Activity {

private Handler myHandler = new Handler();
private Runnable drawRunnable = new Runnable() {

    @Override
    public void run() {
        as();
        myHandler.postDelayed(this, 10000);
    }
};

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_service_demo);

    myHandler.postDelayed(drawRunnable, 10000);

    startService(new Intent(this, MyService.class));
}

public void as(){
    startService(new Intent(this, MyService.class));
}

@Override
protected void onPause() {
    // TODO Auto-generated method stub
    super.onPause();
}
}

Service.java

public class MyService extends Service {

@Override
public IBinder onBind(Intent intent) {
    return null;
}

@Override
public void onCreate() {
    Toast.makeText(this, "HOHO Service Created...", Toast.LENGTH_LONG).show();
}

@Override
public void onDestroy() {
}

@Override
public void onStart(Intent intent, int startid) {
    Toast.makeText(this, "Service Started...", Toast.LENGTH_LONG).show();
}
}

Edit 1

 moveTaskToBack(true);

I put this into the onBackPressed method I Service give the o/p if I am not on the screen but When I kill the App, Service not responding

Upvotes: 0

Views: 1536

Answers (3)

Himanshu Dudhat
Himanshu Dudhat

Reputation: 1609

I think you need to override onStartCommand instead of onStart()

like:

public int onStartCommand(Intent intent, int flags, int startid)
{
   Toast.makeText(this, "Service Started...", Toast.LENGTH_LONG).show();
    return Service.START_STICKY;
}

Upvotes: 1

user2936761
user2936761

Reputation: 51

You have to user AlarmManager, here's an example : Alarm Manager Example

Your task will be executed even if the application is terminated.

But if the application is killed by the user, the Alarm will be canceled. See this discussion How to create a persistent AlarmManager

Upvotes: 0

afpro
afpro

Reputation: 1103

i think AlarmManager is what you want.

Upvotes: 0

Related Questions