android - startService() from the service class itself -
i try start android service service's class. reason achieve platform independence.
doing nullpointerexception @ android.content.contextwrapper.startservice(contextwrapper.java:326). platform target 2.1-update1, suggestions?
see code below (i left imports out save space)
/* gui: helloandroid.java */ package com.example.helloandroid; public class helloandroid extends activity { @override public void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.main); // works! startservice(new intent("com.example.helloandroid.unusualservice")); // stop service works of course, stopservice(new intent("com.example.helloandroid.unusualservice")); // unusual start not work: unusualservice myservice = new unusualservice(); myservice.startservice(); } } /* service: unusualservice.java */ package com.example.helloandroid; public class unusualservice extends service { @override public void oncreate() { toast.maketext(this, r.string.service_started, toast.length_short).show(); } @override public void ondestroy() { toast.maketext(this, r.string.service_stopped, toast.length_short).show(); } @override public ibinder onbind(intent intent) { return null; // make here when rest works } public void startservice() { // folowing line cause nullpointerexception startservice(new intent("com.example.helloandroid.unusualservice")); } public void stopservice() { stopself(); } }
of course - newly created service not have reference context, context null
, therefore system throws nullpointerexception
. remember: not create service on own using new
- system you!
Comments
Post a Comment