Question

I am trying to use usbmanager inside a library i create.

In my library I have:

public class usb_manager extends Service{

   private UsbManager myUsbManager;

        public usb_manager(){
          myUsbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
        }
   }
...
}

then i am trying to call the constructor in another java file

public class MainActivity extends Activity {

public usb_manager testusb = new usb_manager();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

}
 ...
}

the app crashes when it starts.

but if i change the code in my library to, (ie, move the initialization of usbmanager to the activity):

public class usb_manager extends Service{

   private UsbManager myUsbManager;

        public usb_manager(UsbManager in){
          mUsbManager = in;
        }     
...
}

and in MainActivity of my program:

  public class MainActivity extends Activity {


  public usb_manager testusb; = new usb_manager();
  private UsbManager myUsbManager;
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

           myUsbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
            testusb = new usb_manager(myUsbManager);

 }
 ...
 }

it works.

can anyone tell me what is the problem with using myUsbManager = (UsbManager) getSystemService(Context.USB_SERVICE);

inside the library file.

Was it helpful?

Solution

Simply getSystemService() returns null in constructor since Context is not initalized. Override onCreate() in your usb_manager service and assign myUsbManager there. And don't call service constructor in Activity use startService() instead.

See this services tutorial

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top