Intent 打开文件浏览器,返回后得到文件路径

来源:互联网 发布:企业软件上线时刻表 编辑:程序博客网 时间:2024/06/02 18:42
<?xml version="1.0" encoding="utf-8"?><RelativeLayout    xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:paddingBottom="@dimen/activity_vertical_margin"    android:paddingLeft="@dimen/activity_horizontal_margin"    android:paddingRight="@dimen/activity_horizontal_margin"    android:paddingTop="@dimen/activity_vertical_margin"    tools:context="com.demo.gudd.selectmusic.MainActivity">    <Button        android:id="@+id/open"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:text="打开文件"/>    <TextView        android:id="@+id/showPath"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_below="@+id/open"/></RelativeLayout>

package com.demo.gudd.selectmusic;import android.content.Intent;import android.net.Uri;import android.os.Bundle;import android.support.v7.app.AppCompatActivity;import android.view.View;import android.widget.Button;import android.widget.TextView;public class MainActivity extends AppCompatActivity implements View.OnClickListener{    private TextView showPath;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        Button open = (Button) findViewById(R.id.open);        showPath = (TextView) findViewById(R.id.showPath);        open.setOnClickListener(this);    }    @Override    protected void onActivityResult(int requestCode, int resultCode, Intent data) {        if (requestCode == 1 && resultCode == RESULT_OK) {            String  mFilePath = Uri.decode(data.getDataString());            //通过data.getDataString()得到的路径如果包含中文路径,则会出现乱码现象,经过Uri.decode()函数进行解码,得到正确的路径。但是此时路径为Uri路径,必须转换为String路径,网上有很多方法,本人通过对比发现,Uri路径里多了file://字符串,所以采用以下方法将前边带的字符串截取掉,获得String路径,可能通用性不够好,下一步会学习更好的方法。            mFilePath = mFilePath.substring(7, mFilePath.length());            showPath.setText(mFilePath);        }        super.onActivityResult(requestCode, resultCode, data);    }    @Override    public void onClick(View v) {        switch (v.getId()){            case R.id.open:                // 打开系统文件浏览功能                Intent intent = new Intent();                intent.setAction(Intent.ACTION_GET_CONTENT);                intent.setType("*/*");                intent.addCategory(Intent.CATEGORY_OPENABLE);                startActivityForResult(intent,1);                break;        }    }}
                                             
0 0
原创粉丝点击