Получить файл .vcf из приложения «Файлы» в версиях Nougat и Oreo в мое приложение

У меня есть приложение для Android, которое отлично работает в версиях Jelly Bean и Kitkat. Приложение получит файл .vcf как Intent из приложения Диспетчер файлов с помощью параметра Завершить действие с помощью.

Теперь в версиях Android Nougat и Oreo при использовании приложения Файлы есть опция Открыть с помощью или Поделиться, чтобы мое приложение не отображалось в списке.

Как это решить? Заранее спасибо.

AndroidManifest.xml

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

    <uses-permission android:name="android.permission.GET_ACCOUNTS" />

    <uses-permission android:name="android.permission.READ_CONTACTS" />
    <uses-permission android:name="android.permission.WRITE_CONTACTS" />

    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme.CustomOrange"
        >
        <activity>
        ...
        ...
        </activity>
        <activity
            android:name=".ViewContactActivity"
            android:configChanges="orientation|keyboardHidden|screenSize"
            android:label="@string/title_activity_vcf" >

            <intent-filter> <!-- Handle http https requests without mimeTypes: -->
                <action android:name="android.intent.action.VIEW" />

                <category android:name="android.intent.category.BROWSABLE" />
                <category android:name="android.intent.category.DEFAULT" />

                <data android:scheme="http" />
                <data android:scheme="https" />
                <data android:host="*" />
                <data android:pathPattern="/.*\\.vcf" />
            </intent-filter>
            <intent-filter> <!-- Handle with mimeTypes, where the suffix is irrelevant: -->
                <action android:name="android.intent.action.VIEW" />

                <category android:name="android.intent.category.BROWSABLE" />
                <category android:name="android.intent.category.DEFAULT" />

                <data android:scheme="http" />
                <data android:scheme="https" />
                <data android:host="*" />
                <data android:mimeType="text/x-vcard" />
            </intent-filter>
            <intent-filter> <!-- Handle intent from a file browser app: -->
                <action android:name="android.intent.action.VIEW" />
                <action android:name="android.intent.action.INSERT_OR_EDIT" />

                <category android:name="android.intent.category.DEFAULT" />

                <data android:scheme="file" />
                <data android:host="*" />
                <data android:mimeType="text/x-vcard" />
            </intent-filter>
        </activity>
    </application>

</manifest>

ViewContactActivity.java

public  class       ViewContactActivity
        extends     AppCompatActivity {

    private static final String TAG = ViewContactActivity.class.getSimpleName();

    public static final String  VIEW_CONTACT_BY_ID      = "viewContactById";

    private static final int    MODE_VIEW_BY_ID     = 0;
    private static final int    MODE_VIEW_BY_FILE   = 1;
    private int                 viewContactMode;

    private ActionBar mActionBar;
    ContactDetails contactDetails;
    String mFilePath;
    private GroupInfoPickerAlertDialog mGroupInfoPickerAD;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_vcf);


        contactDetails = new ContactDetails(this);
        Intent intent = getIntent();
        Long id = intent.getLongExtra(VIEW_CONTACT_BY_ID, -1L);
        Bitmap bitmap = null;
        if (id != -1L) {
            viewContactMode = MODE_VIEW_BY_ID;
            contactDetails.collectContactDetail(id);
            bitmap = BitmapFactory.decodeStream(new BufferedInputStream(contactDetails.getDisplayPhoto()));
        } else {
            viewContactMode = MODE_VIEW_BY_FILE;
            Uri fileUri = intent.getData();
            mFilePath = fileUri.getPath();
            Log.d(TAG, "onCreate() - file path: " + mFilePath);
            //onCreate() - file path: /path/to/file.vcf

            contactDetails.readVCard2_1(fileUri);
        }


        setSupportActionBar((Toolbar)findViewById(R.id.toolbar));
        mActionBar = getSupportActionBar();

        if(mActionBar == null) {
            Log.d(TAG, "onCreate() mActionBar == null");
        } else {
            Log.d(TAG, "onCreate() mActionBar != null");
        }
        mActionBar.setCustomView(null);
        mActionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_HOME | ActionBar.DISPLAY_SHOW_TITLE);


        contactDetails.displayContact(bitmap);
        if (viewContactMode == MODE_VIEW_BY_FILE) {
            TextView textView = (TextView) findViewById(R.id.message_text_view);
            textView.setText(mFilePath);// + "\n\n" + stringBuilder);
        } else {
            View v = (View) findViewById(R.id.message_text_view).getParent();
            v.setVisibility(View.GONE);
        }
    }

    // ....
    // ....
    // Other codes...
    // ....
    // ....

}

person Chris J    schedule 15.05.2018    source источник
comment
В стандартном Android нет приложения «Файлы». Вам нужно будет связаться с разработчиками этого приложения «Файлы» и спросить их. Или отредактируйте свой вопрос и опубликуйте элемент <activity> (и его дочерние элементы <intent-filter>), и, возможно, мы сможем предложить некоторые улучшения для обеспечения совместимости.   -  person CommonsWare    schedule 15.05.2018
comment
Вопрос @CommonsWare обновлен с кодом   -  person Chris J    schedule 15.05.2018
comment
@CommonsWare Я видел приложение Files в эмуляции Android для доступа к файлам...   -  person Chris J    schedule 15.05.2018


Ответы (1)


Ваши элементы <intent-filter> поддерживают http, https и file. Немногие приложения «файловый менеджер» будут использовать какие-либо из них на Android 7.0+, отчасти потому, что схема file запрещена.

Заменять:

        <intent-filter> <!-- Handle intent from a file browser app: -->
            <action android:name="android.intent.action.VIEW" />
            <action android:name="android.intent.action.INSERT_OR_EDIT" />

            <category android:name="android.intent.category.DEFAULT" />

            <data android:scheme="file" />
            <data android:host="*" />
            <data android:mimeType="text/x-vcard" />
        </intent-filter>

с:

        <intent-filter> <!-- Handle intent from a file browser app: -->
            <action android:name="android.intent.action.VIEW" />
            <action android:name="android.intent.action.INSERT_OR_EDIT" />

            <category android:name="android.intent.category.DEFAULT" />

            <data android:scheme="file" />
            <data android:scheme="content" />
            <data android:mimeType="text/x-vcard" />
        </intent-filter>

Затем убедитесь, что readVCard2_1() обрабатывает схемы file и content Uri, например, вызывая openInputStream() на ContentResolver для доступа к потоку.

person CommonsWare    schedule 15.05.2018
comment
Как получить реальный путь к файлу из содержимого uri? Большинство решений, представленных на stackoverflow.com, связаны с приложением, связанным с камерой. Так что я немного смущен. - person Chris J; 16.05.2018
comment
@ChrisJ: Как получить реальный путь к файлу из содержимого uri? -- нет реального пути к файлу. Вызовите openInputStream() на ContentResolver для доступа к потоку, передав Uri. - person CommonsWare; 16.05.2018
comment
Я хотел бы показать путь, где находится файл, когда файл открывается в Android Activity - person Chris J; 19.05.2018