Pregunta

Tengo una actividad que se inicia un servicio como el que:

    Intent youtubeIntent = new Intent(this, YoutubeFeedService.class);
    service = startService(youtubeIntent);

y para detectar cuando el servicio se detiene utilizo un receptor de radiodifusión:

@Override
public void onResume() {
    IntentFilter filter; 
    filter = new IntentFilter(YoutubeFeedService.NEW_VIDEO_CELL); 
    receiver = new FeaturedReceiver(); 
    registerReceiver(receiver, filter);
    super.onResume();
}

@Override public void onPause() {
    unregisterReceiver(receiver); 
    super.onPause();
}



public class FeaturedReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        String title = intent.getStringExtra("title");


        if (title.equals("-1") || title.equals("1")){
            //stopService(new Intent(FeaturedActivity.this, service.getClass()));
            try {
                Class serviceClass = Class.forName(service.getClassName());
                stopService(new Intent(FeaturedActivity.this, serviceClass));
            } 
            catch (ClassNotFoundException e) {}

        }

    }
}

La primera vez que trató de matar al servicio con

stopService(new Intent(FeaturedActivity.this, service.getClass()));

pero esto no funcionó, así que en vez utilicé

try {
                Class serviceClass = Class.forName(service.getClassName());
                stopService(new Intent(FeaturedActivity.this, serviceClass));
            } 
            catch (ClassNotFoundException e) {}

Y lo hizo el trabajo! ¿Puede alguien explicar cuál es la diferencia?

Gracias

¿Fue útil?

Solución

stopService(new Intent(FeaturedActivity.this, service.getClass()));

En este caso, es un service ComponentName. Por lo tanto, service.getClass() volverá ComponentName.class. Su servicio es YoutubeFeedService.class.

Class serviceClass = Class.forName(service.getClassName());
stopService(new Intent(FeaturedActivity.this, serviceClass));

Parecería más fácil de llamar a:

stopService(new Intent(FeaturedActivity.this, YoutubeFeedService.class);
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top