Android:停止服务的奇怪问题

时间:2010-10-30 11:36:24

标签: android service broadcastreceiver

我有一项活动可以启动这样的服务:

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

并检测服务何时停止我使用广播接收器:

@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) {}

        }

    }
}

我首先尝试使用

终止服务
stopService(new Intent(FeaturedActivity.this, service.getClass()));

但这不起作用,所以改为使用

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

它确实有效!任何人都可以解释有什么区别吗?

由于

1 个答案:

答案 0 :(得分:0)

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

在这种情况下,serviceComponentName。因此,service.getClass()将返回ComponentName.class。您的服务是YoutubeFeedService.class

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

呼叫似乎更简单:

stopService(new Intent(FeaturedActivity.this, YoutubeFeedService.class);