2 つのボタンで開始および停止するバックグラウンド サービスを作成する必要があります。私のサービスは 5 分ごとに循環し、オンライン データベースからデータを取得します。IntentService クラスがループに使用されていないことをどこかで読みました。START_STICKY が返されるように、onStartCommand をオーバーライドします。このクラスでそれを行うと、サービスが開始されません。これどうやってするの?
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();
}
}