(1)如果你需要通过浏览去选择一个你需要的Pic/Music/Video:
//触发代码 Intent intent = new Intent(); intent.setType(“image/*”); //audio/* video/* intent.setAction(Intent.ACTION_GET_CONTENT); startActivityForResult(intent, 1);
//得到返回值,并通过url获取真实路径的方法:重写Activity中的方法 @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == 1) { if (resultCode == RESULT_OK) { Uri uri = data.getData(); // uri=content://media/external/video/media/804 Cursor cursor = managedQuery(uri,null,null,null,null); int index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA); cursor.moveToFirst(); String path = cursor.getString(index); //path=/mnt/sdcard/mediadump/sample.mp4 } } super.onActivityResult(requestCode, resultCode, data); }
1)在AndroidManifest.xml中添加如下过滤器
<intent-filter> <action android:name="android.intent.action.GET_CONTENT" /> <category android:name="android.intent.category.OPENABLE" /> <category android:name="android.intent.category.DEFAULT" /> <data android:mimeType="image/*" /> <data android:mimeType="video/*" /> </intent-filter>这样当另一个程序需要选择视频or图片时,就是提示你是否选择你的程序
2)在代码中添加返回值,一般添加在Click动作的Listener中,点击是获取点击项目触发,代码如下:
if (mActivity.getIntent().equals(Intent.ACTION_GET_CONTENT)) { Intent result = new Intent().setData(mList.get(pos).getContentUri()); mActivity.setResult(Activity.RESULT_OK, result); mActivity.finish(); }//其中mActivity指的是你的MainActivity*********************************************一些相关知识的拓****************************************************
Intent.ACTION_PICK 主要用于向下兼容 / Intent.ACTION_GET_CONTENT 支持使用
通过Intent.ACTION_PICK获取联系人的示例代码
Intent intent = new Intent(Intent.ACTION_PICK, People.CONTENT_URI); startActivityForResult(intent, PICK_CONTACT);
@Override public void onActivityResult(int reqCode, int resultCode, Intent data){ super.onActivityResult(reqCode, resultCode, data); switch (reqCode) { case (PICK_CONTACT) : if (resultCode == Activity.RESULT_OK) { Uri contactData = data.getData(); Cursor c = managedQuery(contactData, null, null, null, null); if (c.moveToFirst()) { String name = c.getString(c.getColumnIndexOrThrow(People.NAME)); }} break; }}