如何获取从服务连接的 USB 设备列表

How to get list of usb devices connected from a service

我正在编写一个 服务,它将一些专有命令发送到连接到基于 Android 的盒子的特定 USB 设备。 早些时候我已经实现了一个应用程序(Activity)所以它非常简单:

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

我的主要class:

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

}

最后我得到:

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

现在没有 activity 我找不到任何方法来获取 UsbManager 的实例。

有没有办法在服务中做到这一点?

getApplicationContextprotected void onHandleIntent(Intent intent) 中有效,所以你必须使用下面的方法来获得 getApplicationContext-

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
mContext = getApplicationContext();
return super.onStartCommand(intent, flags, startId);
}