Getting USBmanager null instance

My Use case is to achieve screencast using MediaProjection API over socket connection (between two wired device):

I have added below permissions for USB access:

<uses-feature android:name="android.hardware.usb.host" />
<uses-permission android:name="android.permission.MANAGE_USB" />
<uses-permission android:name="android.permission.USB_PERMISSION" />
<uses-permission android:name="android.permission.QUERY_ALL_PACKAGES"/>
<uses-permission android:name="android.permission.USB_PERMISSION" />

I have added below intent filters for activity in which I have implemented usb connection:

<intent-filter>
       <action android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED" />
</intent-filter>

<meta-data
       android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED"
       android:resource="@xml/device_filter" />

device_filter.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <usb-device vendor-id="1234" product-id="5678" />
</resources>

Here’s code snippets for USB connection:

Method 1:

class UsbReceiver extends BroadcastReceiver {

    private String TAG = UsbReceiver.class.getSimpleName();

    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (ACTION_USB_PERMISSION.equals(action)) {
            synchronized (this) {
                UsbDevice device = (UsbDevice) intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
                if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
                    if (device != null) {
                        // call method to set up device communication
                    }
                } else {
                    Log.i(TAG, "Permission denied");
                }
            }

        }
    }
}

ServerActivity.java

private UsbManager usbManager;
private UsbDevice usbDevice;
private UsbDeviceConnection usbConnection;
private UsbInterface usbInterface;
private UsbEndpoint endpointIn, endpointOut;
private AppLauncherActivity appLauncherActivity;
private UsbDeviceReceiver usbDeviceReceiver;
private UsbReceiver usbReceiver;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
          usbManager = (UsbManager) getSystemService(context.USB_SERVICE);
          if (usbManager == null) {
            Log.e(TAG, "UsbManager is null after initialization.");
          } else {
            Log.d(TAG, "UsbManager initialized successfully.");
          }
      
    }
    
    usbReceiver = new UsbReceiver();
    PendingIntent mPermissionIntent = PendingIntent.getBroadcast(this, 0, new Intent(
                ACTION_USB_PERMISSION), 0);
    IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);

    registerReceiver(usbReceiver, filter);
    
    for (Map.Entry<String, UsbDevice> dev : usbManager.getDeviceList().entrySet()) {
            if (dev.getValue().getVendorId() == 1234) {
                usbDevice = dev.getValue();
            }
    }

    if (usbDevice != null) {
            if (!usbManager.hasPermission(usbDevice)) {
                usbManager.requestPermission(usbDevice, mPermissionIntent);
            } else {
                Log.d(TAG, "Permission already granted.");
                // Set up USB connection here if permission is already granted
                setupUsbConnection();
            }
    }


    private void setupUsbConnection() {
        if (usbDevice != null) {
            usbConnection = usbManager.openDevice(usbDevice);
            if (usbConnection != null) {
                // Proceed with USB communication setup
                Log.d(TAG, "USB connection established.");
                // Additional code to handle USB data transfer...
            } else {
                Log.e(TAG, "Failed to open USB connection.");
            }
        }
    }

public void startUsbServer() {

//        UsbManager - to access the state of the USB and to communicate with connected hardware peripherals
//        UsbDevice - to communicate with the hardware peripheral if the Android-powered device is acting as the USB host
//        UsbAccessory - if the peripheral is acting as the USB host

        // Discover and set up USB device for communication
        if (usbManager == null) {
//            /questions/28137280/how-to-grant-permission-to-open-usb-device-with-usb-manager-opendevice-always
            Log.e(TAG, "UsbManager is null");
            return;
        } else {
            // or register receiver here
        }

        // Get the list of connected USB devices
        HashMap<String, UsbDevice> deviceList = usbManager.getDeviceList();

        if (deviceList == null || deviceList.isEmpty()) {
            Log.d(TAG, "No USB devices connected");
            return;
        }

        // Iterate through connected devices
        for (UsbDevice device : deviceList.values()) {
            if (device != null) {
                // Get Vendor ID and Product ID
                int vendorId = device.getVendorId();
                int productId = device.getProductId();

                Log.d(TAG, "Vendor ID: " + vendorId);
                Log.d(TAG, "Product ID: " + productId);

                // You can also display this info in your UI or use it as needed

            } else {
                Log.e(TAG, "UsbDevice is null");
            }
        }

    @Override
    public void usbDeviceDetached() {
        Log.d(TAG, "USB Device Detached");
    }

    @Override
    public void usbDeviceAttached(UsbDevice usbDevice) {
        Log.d(TAG, "USB Device Attached: " + usbDevice.getDeviceName());
    }

Method 2:

In Method 2 I’m just creating broadcast receiver differently, and calling this in oncreate():

public class UsbDeviceReceiver extends BroadcastReceiver {

    private String TAG = UsbDeviceReceiver.class.getSimpleName();
    private UsbListener usbListener;

    public void UsbDevicesReceiver(UsbListener usbListener) {
        this.usbListener = usbListener;
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();

        if (UsbManager.ACTION_USB_DEVICE_DETACHED.equals(action)) {
            usbListener.usbDeviceDetached();
        } else if (UsbManager.ACTION_USB_DEVICE_ATTACHED.equals(action)) {
            UsbDevice usbDevice = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
            usbListener.usbDeviceAttached(usbDevice);
        }
    }

    public interface UsbListener {
        void usbDeviceDetached();
        void usbDeviceAttached(UsbDevice usbDevice);
    }
}

Above mentioned is the setup I tried for usb connection but it shows null instance log:

2024-09-12 12:28:31.515  9076-9076  ServerActivity  com.r.screenmediaprojection   E  UsbManager is null

Also, As I’m not able to get usbmanager instance I’m not able to retrieve ccorrect vendor id of my device. I’m connecting two device using C to C cable while building socket connnection.

Please checkout given snippets and share insights to fix this issue…

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật