我有这个后台服务:
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"
在任务/应用程序管理器中我看不到该进程,因此它已停止。 此进程用于安排通知。我知道,它在执行后停止,但是有计时器。
The timer doesn't start.
最佳答案
计时器正在启动,因为调用 onHandleIntent() 后 IntentService 实例不可用。如果您想安排定期计时器,请进行正常服务
关于java - Android 后台服务启动后立即自行关闭,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39164504/