开发者

Service not getting started

I am writing my first service. My activity works well, but when I call 开发者_高级运维my service, it doesn't.

It looks like it's onCreate() is not getting called.

My service code:

public class NeglectedService extends Service {
    public static final String MY_SERVICE = "android.intent.action.MAIN";
    public void onCreate() {
        Toast.makeText(this, "Service onCreate...", Toast.LENGTH_LONG).show();
    }
}

I am not even getting the Toast message.

Here is my activity

startService(new Intent(NeglectedService.MY_SERVICE));

My manifest

action android:name="android.intent.action.MAIN"


Did you enter something like

<service android:name=".subpackagename.ServiceName"/>

into your Android Manifest xml file?


Seeing as the NeglectedService.MY_SERVICE is just a string, in your startService call you're essentially calling:

startService(new Intent("android.intent.action.MAIN"));

Clearly that doesn't have any reference to your particular service and isn't what you want. Instead, either register the service for particular intent filters and include those in your intent, or call it by class:

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


Call your Service using an Explicit intent, instead of using an implicit action string, which should be more unique anyway. In other words, use this in your Activity code:

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

Hope that helps!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜