我有一项服务可以通过按下按钮来工作。 里面有一个每秒都在工作的计数器。 我测试了它并且它有效。 应用程序关闭后它也可以工作。 应用关闭后的问题 然后我就运行 测试服务,它不起作用。 从 Android studio 内部运行后如何使其工作?
//主 Activity
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(!isMyServiceRunning(SensorService.class)){
Log.i("isServiceRunning","Not");
}else {
Log.i("isServiceRunning","Don");
}
}
public void Test(View view){
startService(new Intent(this, SensorService.class));
}
private boolean isMyServiceRunning(Class<?> serviceClass) {
ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (serviceClass.getName().equals(service.service.getClassName())) {
return true;
}
}
return false;
}
}
/// Service
public class SensorService extends Service {
public int counter=0;
public SensorService() {
super();
Log.i("HERE", "here I am!");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
startTimer();
return START_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
Log.i("EXIT", "ondestroy!");
// Intent broadcastIntent = new Intent(this, SensorRestarterBroadcastReceiver.class);
stoptimertask();
}
private Timer timer;
private TimerTask timerTask;
long oldTime=0;
public void startTimer() {
//set a new Timer
Log.i("startTimer", "Don");
timer = new Timer();
//initialize the TimerTask's job
initializeTimerTask();
//schedule the timer, to wake up every 1 second
timer.schedule(timerTask, 1000, 1000); //
}
/**
* it sets the timer to print the counter every x seconds
*/
public void initializeTimerTask() {
Log.i("initializeTimerTask", "Don");
timerTask = new TimerTask() {
public void run() {
Log.i("in_timer", "in timer ++++ "+ (counter++));
}
};
}
/**
* not needed
*/
public void stoptimertask() {
//stop the timer, if it's not already null
if (timer != null) {
timer.cancel();
timer = null;
}
}
@Nullable
@Override
public IBinder onBind(Intent intent){
return null;
}
}
最佳答案
如果您使用 Android Studio 中的“运行”(无论是测试还是应用程序),服务将始终首先停止,因为整个应用程序始终首先停止。如果您从设备手动启动应用程序,该服务不会停止。
没有办法解决这个问题,实际上这是一个很好的功能。它确保应用程序在每次运行时始终干净地启动。如果您想分享这样做的原因,可能有另一种方法可以解决您的问题。
关于java - 如何让应用重启后服务继续工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61139280/