Suppose we create an app and create a service, this is the service code:
public class Servicio extends Service {
public void onCreate(){
super.onCreate();
Toast.makeText(Servicio.this, "Servicio activado ", Toast.LENGTH_SHORT).show();
}
public int onStartCommand(Intent intent, int flags, int startId){
Toast.makeText(Servicio.this, "onStartCommand", Toast.LENGTH_SHORT).show();
return START_STICKY;
}
public void onDestroy(){
Toast.makeText(Servicio.this, "onDestroy", Toast.LENGTH_SHORT).show();
}
public IBinder onBind(Intent intent) {
return null;
}
}
The Activity code:
public class MainActivity extends AppCompatActivity {
private boolean service_status=false;
private Button button;
private Intent intent;
private Servicio servicio=new Servicio();
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_main);
intent=new Intent(getApplicationContext(), Servicio.class);
button=(Button)findViewById(R.id.button);
button.setText("Boton");
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (service_status) {
button.setText("Desactivado");
service_status=!service_status;
stopService(intent);
} else {
button.setText("Activado");
service_status=!service_status;
startService(intent);
}
}
});
}
}
Now moving to another plane, if I execute the application the button has as initial text "Button" and the service_status is equal to false; I click on the button, the service starts and the button changes text to "On" and the service_status changes to true. Now I close the application and reopen it. The button has the text "Button" and the service_status is false even though the service is already ACTIVE. What code does it need to implement to know if the service is activated and with that change the Initial value of the button and service_status text at the moment of starting the application?