我想用一个Activity来启动Service,具体说来是一个IntentService,但是有两个问题:
1)在启动时我的代码
private void switchService(boolean isEnable, String serviceName){
     Intent intent = new Intent();
     intent.setClassName(TestPhoneServiceActivity.this, serviceName);
     if(isEnable){
     startService(intent);
     }
     else{
     if(isServiceRunning(serviceName)){
     stopService(intent);
     while(isServiceRunning(serviceName)){
    
     }
     Toast.makeText(this, "Service stopped Successfully!", Toast.LENGTH_LONG).show();
     } 
     }
    }
但是DDMS报错:Unable to start service Intent { cmp=com.xx.android/.AndroidPhoneService }: not found
但是这个路径是没错的,所以问题出在哪呢?还有,如果我需要调用一个系统服务,是不是也需要将其写到配置文件中啊?
2)之后我用intent.setClass的方法将这个IntentService启动之后,然后用ActivityManager manager = (ActivityManager)getSystemService(ACTIVITY_SERVICE)去查看这个服务对象,结果发现没有在其中,难道是IntentService在结束后就自动destroy掉了吗,IntentService的生命周期跟普通的Service不一样吗?

解决方案 »

  1.   

    service 和 activity一样要在Androimanifest里面申明
      

  2.   

    自定义的Service服务必须在manifest.xml中配置其Service类的详细路径,系统的不需要,某些系统Service只需在Manifest中配置权限即可
      

  3.   

    需要重写构造函数
    public IntentServiceName {
       super(“IntentServiceName ”);
    }
      

  4.   

    你在manifest文件中添加服务了吗?
    不用停止intentservice,它会自动停止的。
    当描述service时能把你的manifest部分代码帖出来吗?
      

  5.   

    楼主不给力啊, 显然是没有配置manifest
      

  6.   

    你应该进入到服务中的类中而不是类的名称
    Intent intent = new Intent();
        intent.setClassName(TestPhoneServiceActivity.this, MyIntentService.class);
        if(isEnable){
            startService(intent);
        }
    intent服务运行结束后,会自己停止。如果你在同一时间开启多个相同的intent服务,这写服务只能顺序执行,所以程序末尾的代码片段是多余的。
    还有一定要在manifest文件中申明服务。