简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM