Разрешения USB не получены приемником вещания - PullRequest
0 голосов
/ 16 марта 2019

Добрый вечер, я достигаю надежд на то, что узнаю о следующей проблеме.

Мое намерение с этим кодом состоит в том, чтобы иметь возможность обрабатывать намерения разрешения USB в приемнике, зарегистрированном в файле манифеста. Приемник получает USB-подключение и отключенные действия, но не USB-разрешения, когда пользователь принимает или отклоняет запрос.

Вот код манифеста, получателя и действия, чтобы отправить запрос на разрешение менеджеру USB. И наконец, мой целевой SDK - 28.

Любая помощь очень ценится. Большое спасибо.

public class BroadcastReceiver extends android.content.BroadcastReceiver{

    public static final String USB_DEVICE_ATTACHED = "android.hardware.usb.action.USB_DEVICE_ATTACHED";
    public static final String USB_DEVICE_DETACHED = "android.hardware.usb.action.USB_DEVICE_DETACHED";
    public static final String USB_PERMISSION ="com.android.example.USB_PERMISSION";

    @Override
    public void onReceive(Context context, Intent intent) {

        Context applicationContext = context.getApplicationContext();

        try{

            if (intent != null) {
                String action = intent.getAction();

                if (!TextUtils.isEmpty(action)) {

                    if (action.equals(USB_DEVICE_ATTACHED) || action.equals(USB_PERMISSION)){

                        UsbDevice device = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
                        UsbManager usbManager = (UsbManager) applicationContext.getSystemService(Context.USB_SERVICE);

                        if (action.equals(USB_DEVICE_ATTACHED)){

                            if (!usbManager.hasPermission(device)){
                                intent.setAction(USB_PERMISSION);
                                intent.putExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false);
                                intent.setClass(applicationContext, PermissionActivity.class);
                                applicationContext.startActivity(intent);
                                Toast.makeText(applicationContext, "Device Attached.", Toast.LENGTH_LONG).show();
                            }
                            else{
                                Toast.makeText(applicationContext, "Permissions already assigned", Toast.LENGTH_LONG).show();
                            }
                        }
                        else if (action.equals(USB_PERMISSION)){

                            if (usbManager.hasPermission(device)){
                                Toast.makeText(applicationContext, "USB Permissions are granted.", Toast.LENGTH_LONG).show();
                            }
                        }
                    }
                    else if (action.equals(USB_DEVICE_DETACHED)) {
                        Toast.makeText(applicationContext, "Device Detached.", Toast.LENGTH_LONG).show();
                    }
                }
            }
        }
        catch(Exception e){
            Toast.makeText(applicationContext, e.getMessage(), Toast.LENGTH_LONG).show();
        }
    }
}

Вот активность:

    public class PermissionActivity extends android.support.v7.app.AppCompatActivity {

    public static final String USB_PERMISSION ="com.android.example.USB_PERMISSION";

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        Context applicationContext = this.getApplicationContext();

        Intent intent = getIntent();
        if (intent != null )
        {
            if (intent.getAction().equals(USB_PERMISSION)){
                if (!intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false )) {
                    UsbDevice device = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
                    if (device != null) {
                        UsbManager mUsbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
                        PendingIntent mPermissionIntent = PendingIntent.getBroadcast(applicationContext, 0, new Intent(USB_PERMISSION), 0);
                        mUsbManager.requestPermission(device, mPermissionIntent);

                        Toast.makeText(applicationContext, "Requesting Permission", Toast.LENGTH_LONG).show();
                    }
                }
            }
        }
        finish();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }
}

И, наконец, файл манифеста.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.user.usbtest">

    <uses-feature android:name="android.hardware.usb.host"/>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <activity
            android:name=".PermissionActivity"
            android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|screenSize"
            android:excludeFromRecents="true"
            android:exported="true"
            android:noHistory="true"
            android:process=":UsbEventReceiverActivityProcess"
            android:taskAffinity="com.example.taskAffinityUsbEventReceiver"
            android:theme="@style/Theme.AppCompat.Translucent">

            <intent-filter>
                <action android:name="com.android.example.USB_PERMISSION"/>
            </intent-filter>
        </activity>

        <receiver android:name=".BroadcastReceiver"
            android:exported="true">
            <intent-filter>
                <action android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED"/>
                <action android:name="android.hardware.usb.action.USB_DEVICE_DETACHED"/>
                <action android:name="com.android.example.USB_PERMISSION"/>
                <action android:name="android.intent.action.BOOT_COMPLETED"/>
            </intent-filter>
        </receiver>
    </application>
</manifest>

1 Ответ

0 голосов
/ 18 марта 2019

Я нашел проблему.Начиная с Android 8.0, существуют дополнительные ограничения для заявленных в декларации широковещательных приемников и типа действий, которые можно получить.Действие USB Permissions не является частью ограниченного списка действий, которые можно получить.Вот несколько ссылок по этой проблеме.

https://developer.android.com/guide/components/broadcasts#context-registered-recievers https://developer.android.com/guide/components/broadcast-exceptions

...