BertalanD
BertalanD

Reputation: 33

Android Background service closes itself instantly when starting it

I have this background service:

public class UjsagFeedReaderService extends IntentService {

public UjsagFeedReaderService(){
    super("UjsagFeedReaderService");
}

    Timer timerbd = new Timer();
    TimerTask taskbd = new TimerTask() {
        public int a = 0;
        @Override
        public void run() {
            a++;
            Toast.makeText(getBaseContext(), "Letelt egy perc, új cikkek keresése. (debug infó)", Toast.LENGTH_LONG).show();
           debug();
            Log.w("logd", "megy");

        }
    };

@Override
protected final void onHandleIntent(Intent workIntent) {
    Log.w("logd", "run");
    boolean run = workIntent.getBooleanExtra("Belfold",false);
    boolean Belfold = workIntent.getBooleanExtra("Belfold",false);
    boolean Kulfold = workIntent.getBooleanExtra("Kulfold",false);
    boolean Gazdasag = workIntent.getBooleanExtra("Gazdasag",false);
    boolean TudTech = workIntent.getBooleanExtra("TudTech",false);
    boolean Sport = workIntent.getBooleanExtra("Sport",false);
    boolean Eletmod = workIntent.getBooleanExtra("Eletmod",false);
    boolean Kultura = workIntent.getBooleanExtra("Kultura",false);
    boolean Autok = workIntent.getBooleanExtra("Autok",false);
    boolean Egeszseg = workIntent.getBooleanExtra("Egeszseg",false);
    try {
        timerbd.scheduleAtFixedRate(taskbd, 60000, 60000);
    }
    catch(Exception ex) {
        Toast.makeText(getBaseContext(), "Hiba", Toast.LENGTH_LONG).show();
    }
    }

public void debug(){

    NotificationCompat.Builder mBuilder =
            new NotificationCompat.Builder(this)
                    .setSmallIcon(R.mipmap.ic_launcher)
                    .setContentTitle("Teszt")
                    .setContentText("Szia. Ez csak egy teszt" );
    NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

    mNotificationManager.notify(2004, mBuilder.build());
}
@Override
public void onDestroy() {
    Toast.makeText(this, "Mostantól nem fognak értesítések megjelenni.", Toast.LENGTH_LONG).show();
    timerbd.cancel();
}

}

But when I start it, with:

Intent in = new Intent(getBaseContext(), UjsagFeedReaderService.class);
MainActivity.this.startService(in);

it instantly stops, runs the "OnDestroy method"

In the task/application manager I can't see the process, so it's stopped. This process is used for scheduling notifications. I know, that it stops after executing, but there is the timer.

The timer doesn't start.

Upvotes: 0

Views: 93

Answers (1)

Mohammad Misbah
Mohammad Misbah

Reputation: 1074

timer is starting because IntentService instance is not available after calling onHandleIntent(). If you want schedule regular timer kindly go through with normal services

Upvotes: 4

Related Questions