我正在编写service,它将向与基于Android的盒子相连的特定USB设备发送一些专有命令。之前我已经实现了一个带有Activity的应用程序,所以它非常简单:
UsbManager manager = (UsbManager) getSystemService(Context.USB_SERVICE);
我的主班:
public class MyService extends IntentService {
..
mUsbManager = (UsbManager) getApplicationContext().getSystemService(USB_SERVICE);
}
我最终得到:
java.lang.NullPointerException:尝试调用虚拟方法'android.content.Context空对象上的android.content.Context.getApplicationContext()'参考
现在没有活动,我找不到任何方法来获取UsbManager的实例。
是否可以在服务中执行此操作?
[getApplicationContext
确实可以在protected void onHandleIntent(Intent intent)
中使用,因此您必须使用以下方法来获取getApplicationContext
-
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
mContext = getApplicationContext();
return super.onStartCommand(intent, flags, startId);
}