public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn= (Button) findViewById(R.id.btn);
btn.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);
startActivityForResult(intent,1);
}
});
}
}
//intent.setType(“image/*”);//选择图片
//intent.setType(“audio/*”); //选择音频
//intent.setType(“video/*”); //选择视频 (mp4 3gp 是android支持的视频格式)
//intent.setType(“video/*;image/*”);//同时选择视频和图片
onActivityResult函数响应了选择文件的操作。
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK) {
if (requestCode == 1) {
Uri uri = data.getData();
Toast.makeText(this, "文件路径:"+uri.getPath().toString(), Toast.LENGTH_SHORT).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("*/*");
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();
}
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
if (resultCode != Activity.RESULT_OK) {
Log.e(TAG, "onActivityResult() error, resultCode: " + resultCode);
super.onActivityResult(requestCode, resultCode, data);
return;
}
if (requestCode == FILE_SELECT_CODE) {
Uri uri = data.getData();
Log.i(TAG, "------->" + uri.getPath());
}
super.onActivityResult(requestCode, resultCode, data);
}