0

所有教程都告诉我这样做:

startService(new Intent(this, MyService.class));

但是没有构造函数接受 Activity、Class,所以我得到语法错误

http://developer.android.com/reference/android/content/Intent.html

我正在尝试以这种方式生成服务,

startService(new Intent(getApplicationContext(), MyService.class));

但我的服务永远不会执行。

public class MyService extends IntentService {                                                                                                                                                                     

    public MyService() {                                                                                                                                                                                           
        super("MyService");                                                                                                                                                                                        
    }                                                                                                                                                                                                                  

    @Override                                                                                                                                                                                                          
    protected void onHandleIntent(Intent intent) {                                                                                                                                                                     
        //do stuff                                                                                                                                                                                                     
    }                                                                                                                                                                                                                  

}  

我怎样才能产生服务?

答案:我的 android manifest 没有特定的包

4

2 回答 2

2

此处添加的实际问题(如评论中所示):

该服务位于不同的包中,因此在清单中它必须是完全合格的,例如<service android:name="actual.package.of.MyService"/>

老答案:

  1. 如果您尝试在内部类中启动服务,则不应编写:

    startService(new Intent(this, MyService.class));
    

    但:

    startService(new Intent(ActivityName.this, MyService.class));
    
  2. 确保您的服务出现在清单中。

  3. 在内部添加调试打印onHandleIntent以查看它是否启动。
于 2012-05-02T15:58:59.717 回答
0

服务不是可见的

可能您尚未在清单文件中声明该服务。

我不认为代码有任何问题。覆盖 onstartCommand 和 oncreate 方法,只需放置一条日志语句并检查 logcat

于 2012-05-02T15:59:51.030 回答