!Android选择文件返回路径

最近刚忙完给的task 捡起了好久好久之前没做好的OTAupdate..

(关于选择文件返回路径,复制到cache/recovery这件事!!)

下面是选择文件返回路径的demo:

1.activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/about_page"
    android:paddingLeft="10dp"
    android:paddingRight="10dp"
    android:orientation="vertical">


    <Button
        android:id="@+id/open_btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="open file picker"
        android:textSize="25dp"/>
    <TextView
        android:id="@+id/testText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="18sp"
        android:text=" path:">
    </TextView>
    <Button
        android:id="@+id/next_btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="next"
        />
</LinearLayout>

2.MainActivity.java(因我这边有用到下一个activty,所以使用时nextBtn部分需要修改一下😁)

package com.oem.otapackageupdate;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "OTAPackageUpdate";

    private Context context;
    private TextView testText;

    Button openBtn;
    Button nextBtn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        context = getApplicationContext();
        testText=  findViewById(R.id.testText);
        openBtn = findViewById(R.id.open_btn);
        nextBtn = findViewById(R.id.next_btn);

        openBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                intent.addCategory(Intent.CATEGORY_OPENABLE);
                intent.setType("*/*");
                startActivityForResult(intent, 102);
            }
        });
    }
    @Override
    protected void onActivityResult(final int requestCode, final int resultCode, @Nullable final Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data == null) {
            // if never choose file,return
            return;
        }
        String path =  FileUtils.getChooseFileResultPath(data.getData(),getApplicationContext());

        testText.setText(path);

        Log.d(TAG,"path:"+ path);

        String nextPath = testText.getText().toString();

        nextBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this,PromptActivity.class);
                intent.putExtra("update file",nextPath);
                Log.d(TAG,"UPDATE FILE: "+ nextPath);
                startActivity(intent);
            }
        });

    }
}

3.FileUtils.java

package com.oem.otapackageupdate;


import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;


public class FileUtils {



    /**
     * get uri path
     *
     * @param uri
     * @return
     */
    public static String getChooseFileResultPath(Uri uri,Context context) {
        String chooseFilePath = null;
        if ("file".equalsIgnoreCase(uri.getScheme())) {//
            chooseFilePath = uri.getPath();
            return chooseFilePath;
        }
        //after 4.4
        chooseFilePath = getPath(context, uri);
        return chooseFilePath;
    }

    private static String getRealPathFromURI(Uri contentUri,Context context) {
        String res = null;
        String[] proj = {MediaStore.Images.Media.DATA};
        Cursor cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
        if (null != cursor && cursor.moveToFirst()) {
            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            res = cursor.getString(column_index);
            cursor.close();
        }
        return res;
    }
    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is ExternalStorageProvider.
     */
    private static boolean isExternalStorageDocument(Uri uri) {
        return "com.android.externalstorage.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is DownloadsProvider.
     */
    private static boolean isDownloadsDocument(Uri uri) {
        return "com.android.providers.downloads.documents".equals(uri.getAuthority());
    }

    
    private static String getPath(final Context context, final Uri uri) {


        // DocumentProvider
        if (DocumentsContract.isDocumentUri(context, uri)) {
            // ExternalStorageProvider
            if (isExternalStorageDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];
                return Environment.getExternalStorageDirectory() + "/" + split[1];
            }
            // DownloadsProvider
            else if (isDownloadsDocument(uri)) {
                final String id = DocumentsContract.getDocumentId(uri);
                final Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
                return getDataColumn(context, contentUri, null, null);

            }
            // MediaProvider
            else if (isMediaDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];

                Uri contentUri = null;
                if ("image".equals(type)) {
                    contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;

                } else if ("video".equals(type)) {
                    contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;

                } else if ("audio".equals(type)) {
                    contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;

                }

                final String selection = "_id=?";
                final String[] selectionArgs = new String[]{split[1]};

                return getDataColumn(context, contentUri, selection, selectionArgs);

            }

        }
        // MediaStore (and general)
        else if ("content".equalsIgnoreCase(uri.getScheme())) {
            return getDataColumn(context, uri, null, null);

        }
        // File
        else if ("file".equalsIgnoreCase(uri.getScheme())) {
            uri.getPath();

        }
        return null;
    }


    private static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {
        Cursor cursor = null;
        final String column = "_data";
        final String[] projection = {column};
        try {
            cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
                    null);
            if (cursor != null && cursor.moveToFirst()) {
                final int column_index = cursor.getColumnIndexOrThrow(column);
                return cursor.getString(column_index);
            }
        } finally {
            if (cursor != null)
                cursor.close();
        }
        return null;
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is MediaProvider.
     */
    private static boolean isMediaDocument(Uri uri) {
        return "com.android.providers.media.documents".equals(uri.getAuthority());
    }

}

❗贴一下大佬写的 很好用!!(🙇‍感谢 终于完成了555)

android 选取本地和SD卡文件并且返回文件路径_android进入sd卡选择文件并返回文件路径-CSDN博客

再贴一点运行截图haha

  • 点击openBtn之后会弹出系统自带的文件管理器

  • 可以选择(sdcard,udisk)[因为用的虚拟机 所以截图只有这些]

  • 选择sdcard,然后再选中文件,点右上角SELECT

  • 然后就会有返回路径出来啦!🆒

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值