StartService () from the service class itself

I am trying to start android service from service class. The reason for this is to achieve some platform independence.

By doing this, I get a NullPointerException in the file android.content.ContextWrapper.startService (ContextWrapper.java:326). The purpose of the platform is 2.1-update1, any suggestions?

See the code below (I left the import to save some 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); // that works! startService(new Intent("com.example.helloandroid.UnusualService")); // stop the service works of course, too stopService(new Intent("com.example.helloandroid.UnusualService")); // unusual start does 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 something here when the rest works } public void startService() { // folowing line will cause the NullPointerException startService(new Intent("com.example.helloandroid.UnusualService")); } public void stopService() { stopSelf(); } } 
+4
source share
3 answers

Of course, your newly created service has no context reference, therefore the context is null , and therefore the system throws a NullPointerException . Remember: do not create the service yourself using new - the system does it for you!

+9
source

Your UnusualService extends Service . The service extends ContextWrapper , which contains Context . So when you call UnusualService.startService(new Intent("...")) , it actually calls ContextWrapper.startService() , which calls context.startService() . However, at this point, the context is null and NullPointerException .

 public abstract class Service extends ContextWrapper implements ComponentCallbacks { private static final String TAG = "Service"; public Service() { super(null); } //... } public class ContextWrapper extends Context { Context mBase; public ContextWrapper(Context base) { mBase = base; } @Override public ComponentName startService(Intent service) { return mBase.startService(service); } //... } 
+3
source
 public void startService() { // folowing line will cause the NullPointerException startService(new Intent("com.example.helloandroid.UnusualService")); } 

do it instead ...

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

Edit: Fixed according to Cypriot

+2
source

All Articles