Call MainActivity variable to a service class in Android Studio

0

I have an application that gets the user's location, now I need to send those values (latitude, longitude) when launching a service ..

//Variables donde se guardan las coordenadas
Double lati = new Double(0);
Double longi = new Double(0);

//Variables para convertir a String las coordenadas
public String latis = Double.toString(lati);
public String longis = Double.toString(longi);    

protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // Método para obtener la ubicación
    locationStart();

    // Se lanza el servicio
    startService(new Intent(this, ServiceDemo.class));
}

How can I pass these variables?

I tried to get the location from the Service class, but it marked me error when casting to MainActivity. So I opted to go directly through the variables, but I still can not find any solution.

    
asked by Agus Olivera 17.05.2018 в 06:54
source

2 answers

1

As Pablo says, the best thing you can do is pass data in the intent.

Intent intent = new Intent(this, ServiceDemo.class);
intent.putExtra("latis", latis);
intent.putExtra("longis", longis);
startActivity(intent);

And in your Service Demo class ...

String latis_service = getIntent().getStringExtra("latis");
String longis_service = getIntent().getStringExtra("longis");
    
answered by 17.05.2018 в 10:08
0

You would send an Intent that is directed to your precise class. Something like that in the Activity:

Intent intent = new Intent(this, Servicio.class);
intent.putExtra("nameVar",data);
startService(intent);

and in the service like this:

@Override
public int onStartCommand (Intent intent, int flags, int startId) {
    String stringVar = intent.getStringExtra("nameVar");
    System.out.println(stringVar);
return START_NOT_STICKY;
}
    
answered by 07.12.2018 в 16:48