package com.mytest.filemanger;
import android.app.*;
import android.content.*;
import android.database.*;
import android.net.*;
import android.os.*;
import android.provider.*;
import android.support.v7.app.*;
import android.view.*;
import android.widget.*;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button btn= (Button) findViewById(R.id.btn);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
chooseFile();
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("text/xls");//设置类型,我这里是任意类型,任意后缀的可以这样写。
//intent.setType(“audio/*”)
//intent.setType(“image/*”);//选择图片
//intent.setType(“audio/*”); //选择音频
//intent.setType(“video/*”); //选择视频 (mp4 3gp 是android支持的视频格式)
//intent.setType(“video/*;image/*”);//同时选择视频和图片
intent.addCategory(Intent.CATEGORY_OPENABLE);
startActivityForResult(intent,1);
}
});
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
TextView textview=(TextView)findViewById(R.id.fileurl);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == 1) {
Uri uri = data.getData();
textview.setText(getFilePathFromUri(this, uri) );
//Toast.makeText(this, "文件路径:"+uri.getPath().toString(), Toast.LENGTH_LONG).show();
}
}
}
private static final int FILE_SELECT_CODE = 0;
private static final String TAG = "VideoActivity";
private void chooseFile() {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("text/xls");
intent.addCategory(Intent.CATEGORY_OPENABLE);
try {
startActivityForResult(Intent.createChooser(intent, "选择文件"), FILE_SELECT_CODE);
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(this, "亲,木有文件管理器啊-_-!!", Toast.LENGTH_SHORT).show();
}
}
public static String getFilePathFromUri(Context context, Uri uri) {
if (null == uri) return null;
final String scheme = uri.getScheme();
String data = null;
if (scheme == null)
data = uri.getPath();
else if (ContentResolver.SCHEME_FILE.equals(scheme)) {
data = uri.getPath();
} else if (ContentResolver.SCHEME_CONTENT.equals(scheme)) {
Cursor cursor = context.getContentResolver().query(uri, new String[]{MediaStore.Images.ImageColumns
.DATA}, null, null, null);
if (null != cursor) {
if (cursor.moveToFirst()) {
int index = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
if (index > -1) {
data = cursor.getString(index);
}
}
cursor.close();
}
}
return data;
}
}
网友评论