【发布时间】:2018-11-05 06:01:57
【问题描述】:
我正在一个应用程序中工作,我需要在每 60 分钟后刷新一次令牌。我创建了一个在后台运行的服务。但是,我面临的问题是,当手机进入睡眠模式时,我的服务会停止,因此我无法刷新我的令牌。我主要是在 OREO 和 PIE 中遇到这个问题。
public class InActivityTimer extends Service {
@Override
public void onCreate() {
super.onCreate();
mService = APIUtils_AI.getSOService();
mService2 = APIUtils_AI.getSOServiceAI();
utils = new Utils();
receiver = new BroadcastTokenCheck();
filter = new IntentFilter(COUNTDOWN_BR);
registerReceiver(receiver, filter);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
cdt = new CountDownTimer(15000, 1000) {
@Override
public void onTick(long millisUntilFinished) {
Log.i(TAG, "Countdown seconds remaining: " + millisUntilFinished / 1000);
if(millisUntilFinished<8000&&millisUntilFinished>5000){
if(!isSecond){
Log.i("", "Running: ");
refreshToken();//Refresh Token API
cdt.cancel();
cdt.start();
}
}
}
@Override
public void onFinish() {
Intent intent = new Intent(COUNTDOWN_BR);
intent.putExtra("VALUE","startService");
sendBroadcast(intent);
//stopSelf();
Log.i("", "Timer finished");
}
}.start();
return START_STICKY;
}
@Override
public void onDestroy() {
unregisterReceiver(receiver);
Log.e("Service Status: ","Stopped");
cdt.cancel();
super.onDestroy();
}
@Override
public IBinder onBind(Intent arg0) {
return null;
}
}
【问题讨论】:
-
有更好的方法来安排代码执行,比如 JobScheduler,但是如果你希望你的服务在后台运行总是,你必须实现一个前台服务
标签: java android android-service android-8.0-oreo