我杀死不需要的应用程序时,我的服务被操作系统杀死。我想为某些工作运行后台服务。请指导我该怎么做。
这是服务类代码:
public class MyThreadClass extends Service {
Handler handler;
Runnable runnable;
private static final String TAG = "MyThreadClass";
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
handler=new Handler();
runnable=new Runnable() {
@Override
public void run() {
Log.d(TAG, "run: Runnging in Background");
handler.postDelayed(this,1000);
}
};
handler.postDelayed(runnable,1000);
return START_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy: Called");
//handler.removeCallbacks(runnable);
}
}
清单声明:
<service android:name=".MyThreadClass"></service>
请指导我如何在后台正确运行服务
答案 0 :(得分:0)
您可以使用CountDownTimer,下面是相同的代码,希望对您有所帮助。
public class MyThreadClass extends Service {
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
CountDownTimer countDownTimer = new CountDownTimer(5000, 1000) {
@Override
public void onTick(long millisUntilFinished) {
//calls after every 500ms
// do something
}
@Override
public void onFinish() {
//calls after finishtime 5000ms
//do something
}
};
}
@Override
public void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy: Called");
}
}