我是使用服务类的新手,我想启动后台服务,但是由于Android后台限制,我遇到了问题,因为我的手机是Oreo API = 27。因此,我将代码更改为JobIntentService,但是当我尝试无限代码时,android系统强制终止该服务,并再次安排重新启动。但是我需要它无限运行(我知道电池会耗尽,但这是必需的。)
我的应用程序将在特定时间段内(例如5秒)读取文件内容,如果已更改,它将根据myCode中的某些逻辑更新其他文件,并且该应用程序没有活动类,也没有UI。
MyReceiver.java是
//@RequiresApi(api = Build.VERSION_CODES.O)
//I have logic for check API 26+ and 26-
@Override
public void onReceive(Context context, Intent intent) {
//intent action filtered but not showed because make it more readable.
MyService.enqueueWork(context,myIntent); //myIntent is assigned previously code but not showed.
context.startForegroundService(myIntent);
}
MyService.java是
@Override
public void onCreate() {
super.onCreate();
startForeground(NOTIFICATION_ID, notification); //notification is set previously code but not showed.
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d(TAG, "myService Started!");
//do infinite loop here but it fails because of time-out.
while (true){
//my code
if(cond)break;
}
return super.onStartCommand(intent, flags, startId);
}
更新: 我更新了myService来启动处理程序,它现在可以工作,但是我仍然不知道android系统如何杀死处理程序,如果强制杀死我不知道如何强制重启。
MyService.java更新为:
public class MyService extends JobIntentService {
private Handler=new Handler();
Runnable runnable=new Runnable() {
@Override
public void run() {
if (a>=Integer.MAX_VALUE-1)
a=0;
Log.d(TAG,"RunningHandler_"+ ++a +"_times");
try {
Thread.sleep(1000); //1s sleep
} catch (InterruptedException e) {
e.printStackTrace();
}
handler.postDelayed(runnable,0);
}
};
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d(TAG, "myService Started!");
handler.postDelayed(runnable,0);
return super.onStartCommand(intent, flags, startId);
}
}