2012-11-20 99 views
0

我想启动服务使用活动。具体来说,它是IntentService。但我有两个问题:启动服务使用活动

当开始我的代码

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

但道路是正确的。那么问题是什么呢?我也想调用一个系统服务。我应该把它写入配置文件吗?

然后我启动IntentService使用intent.setClass。

ActivityManager manager = (ActivityManager)getSystemService(ACTIVITY_SERVICE) 

我找不到这个服务对象。 IntentService是否自动完成并销毁?IntentService的生命周期与其他Service不同?

+1

你是否在清单文件中添加了你的服务? –

+0

不停止intentservice,它在完成时自行停止 – njzk2

+0

发布您描述服务的清单部分 – njzk2

回答

0

你应该通过在类的服务,而不是类的服务的名称,像这样

Intent intent = new Intent(); 
    intent.setClassName(TestPhoneServiceActivity.this, MyIntentService.class); 
    if(isEnable){ 
     startService(intent); 
    } 

如果你开始的目的相同服务的多个意向服务停止自己的工作完成后,它会排在后面并按顺序执行,所以else块在你的情况下是多余的。

并确保您在清单中声明了服务。