0

I am writing a service which would send some proprietary commands to a specific USB device connected to Android based box. Earlier I had implemented an app (with Activity) so it was pretty straightforward:

UsbManager manager = (UsbManager) getSystemService(Context.USB_SERVICE);

My main class:

public class MyService extends IntentService {
 ..
 mUsbManager = (UsbManager) getApplicationContext().getSystemService(USB_SERVICE);

}

And I end up with :

java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference

Now without an activity I am not finding any ways to get an instance of UsbManager.

Is there a way to do this in a service?

Ketan Ahir
  • 6,678
  • 1
  • 23
  • 45
Sabin
  • 61
  • 3

1 Answers1

1

getApplicationContext does work in protected void onHandleIntent(Intent intent) so you have to use below method to get getApplicationContext-

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
mContext = getApplicationContext();
return super.onStartCommand(intent, flags, startId);
}
Dipankar Baghel
  • 1,932
  • 2
  • 12
  • 24