Android: Weird issue in stopping a service
I have an activity that starts a service like that:
Intent youtubeIntent = new Intent(this, YoutubeFeedService.class);
service = startService(youtubeIntent);
and to detect when the service stops I use a broadcast receiver:
@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) {}
}
}
}
I first tried to kill the service with
stopService(new Intent(FeaturedActivity.this, service.getClass()));
but this didn't work, so instead I used
try {
Class serviceClass = Class.forName(service.getClassName());
stopService(new Intent(FeaturedActivity.this, serviceClass));
}
catch (ClassNotFoundException e) {}
And it did work! Can a开发者_运维百科nyone explain what's the difference?
Thanks
stopService(new Intent(FeaturedActivity.this, service.getClass()));
In this case, service
is a ComponentName
. Hence, service.getClass()
will return ComponentName.class
. Your service is YoutubeFeedService.class
.
Class serviceClass = Class.forName(service.getClassName());
stopService(new Intent(FeaturedActivity.this, serviceClass));
It would seem simpler to call:
stopService(new Intent(FeaturedActivity.this, YoutubeFeedService.class);
精彩评论