我需要创建一个通过两个按钮启动和停止的后台服务。我的服务每 5 分钟循环一次,它会从在线数据库中获取数据。我在某处读到 IntentService 类不用于循环。我会覆盖 onStartCommand,所以它会返回 START_STICKY。如果我在这堂课上这样做,我的服务将不会启动。我怎样才能做到这一点?
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void start(View view){
startService(new Intent(this, ForegroundService.class));
}
public void stop(View view){
stopService(new Intent(this, ForegroundService.class));
}
}
public class ForegroundService extends IntentService{
private boolean stato;
public ForegroundService(){
super("ForegroundService");
}
@Override
public void onCreate(){
super.onCreate();
Toast.makeText(this, "Service Started", Toast.LENGTH_SHORT).show();
}
@Override
protected void onHandleIntent(Intent i){
stato = true;
int n=0;
while(stato)
{
Log.i("PROVA SERVICE", "Evento n."+n++);
try {
Thread.sleep(1000);
}
catch (InterruptedException e)
{ }
}
}
@Override
public void onDestroy() {
stato = false;
Toast.makeText(this, "service done", Toast.LENGTH_SHORT).show();
super.onDestroy();
}
}