美文网首页
Android工具之启动文件选择器

Android工具之启动文件选择器

作者: sssssss_ | 来源:发表于2019-08-08 11:16 被阅读0次
    public class MainActivity extends AppCompatActivity {
    
        private Button mBtnFileInput;
        private static final int FILE_SELECT_CODEB = 1;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            mBtnFileInput = findViewById(R.id.btn_input);
            mBtnFileInput.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                    intent.setType("*/*");//设置类型
                    intent.addCategory(Intent.CATEGORY_OPENABLE);
                    try {
                        startActivityForResult(Intent.createChooser(intent, "选择文件"),
                                FILE_SELECT_CODEB);
                    } catch (android.content.ActivityNotFoundException ex) {
                        LogUtils.v("没有找到想要的文件");
                    }
                }
            });
        }
    
        @Override
        protected void onActivityResult(int requestCode, int resultCode, Intent data) {
            if (resultCode == Activity.RESULT_OK) {
                if (requestCode == 1) {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                        //高于API19版本
                        String[] split = data.getData().getPath().split("\\:");
                        String p = "";
                        if (split.length >= 2) {
                            p = Environment.getExternalStorageDirectory() + "/" + split[1];
                            LogUtils.v(p);
                            boolean mainthread = Looper.getMainLooper() == Looper.myLooper();
                            LogUtils.v(mainthread + "");
                            new ReadFileTask().execute(p);
                        }
                    } else {
                        //低于API19版本
                        Uri uri = data.getData();
                        LogUtils.v("文件路径" + uri.getPath());
                    }
                }
            }
        }
    }
    
    image.png image.png

    相关文章

      网友评论

          本文标题:Android工具之启动文件选择器

          本文链接:https://www.haomeiwen.com/subject/jjwtjctx.html