public class MainActivity extends AppCompatActivity {
Intent intent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onButton1Clicked(View v) {
intent = new Intent(this, BaseService.class);
startService(intent);
}
public void onButton2Clicked(View v) {
intent = new Intent(this, BaseService.class);
stopService(intent);
}
}
///////////////////////////////////////////////////////////////////////////////////////
public class BaseService extends Service {
Boolean running = true;
int count = 1;
public BaseService() {
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
while (running) {
try {
Log.d ("BaseService", count + "Burn service works");
count++;
Thread.sleep(1000);
} } catch (Exception e) {
Log.e("BaseService", e.toString());
}
}
}
});
thread.start();
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
running = false;
super.onDestroy();
}
@Override
public IBinder onBind(Intent intent) {
// // TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
}
In the example above, when you press the button, the service starts when you press button 1, the count increases, and when you press button 2, the service ends. There is no problem with the example itself in implementing it, but I have a question.
When I press button 1 to run the service and exit the application, the count is initialized a few seconds later and the service starts again from 0. May I know why the count starts again?
android
The service appears to have been shut down by the system and then re-run. The service can be terminated by the system and determines whether the service is restarted by the onStartCommand()
function return value.
The default value of START_STICKY(or START_STICKY_COMPATIBILITY)
is operated because the super.onStartCommand()
value was returned from the code you uploaded. START_STICKY
is the setting to run again when the service is forced to shut down. As a result, you can see the count running from zero as the service restarts.
Please refer to the link below for the relevant explanation.
© 2024 OneMinuteCode. All rights reserved.