Добавьте этот код в Manifest
<receiver
android:name=".MainActivity$BootUpReceiver"
android:enabled="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</receiver>
Затем запустите приемник вещания в MainActivity
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(bootupreceiver);
}
public class BootUpReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
Log.e("USB", "Decive Connected -> " + action);
if (action.equalsIgnoreCase(ACTION_USB_ATTACHED)) {
UsbDevice device = (UsbDevice) intent
.getParcelableExtra(UsbManager.EXTRA_DEVICE);
if (device != null) {
tv_otg.setText("External OTG storage device connected !");
Log.e("true", "true");
}
} else if (action.equalsIgnoreCase(ACTION_USB_DETACHED)) {
tv_otg.setText("External OTG storage device disconnected !");
Log.e("false", "false");
}
}
}
Также добавьте в oncreate () для целей регистрации. Необходимо отменить регистрацию в методе onDestroy ().
bootupreceiver = new BootUpReceiver();
IntentFilter filter = new IntentFilter(ACTION_USB_ATTACHED);
filter.addAction(ACTION_USB_DETACHED);
filter.setPriority(100);
registerReceiver(bootupreceiver, filter);