有时候我们需要将一张图片或者文件从文件管理器中分享到我们自己的app中。
1 我们需要在配置文件中配置下面的信息,才能让别人找到我们的app。
注意是在起始界面的信息中配置
<intent-filter android:label="@string/app_name" >
<action android:name="android.intent.action.SEND" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="*/*" />
</intent-filter>
这个是任意的文件,没有指定文件类型。当然也有针对单独类型的。
<intent-filter>
<action android:name="android.intent.action.SEND" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="file" />
<data android:mimeType="*/*" />
<data android:pathPattern=".*\\.pdf" />
<data android:host="*" />
</intent-filter>
这个是pdf文件。
<intent-filter>
<action android:name="android.intent.action.SEND" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="image/jpeg" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.SEND" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="image/png" />
</intent-filter>
这个是图片。
<intent-filter>
<action android:name="android.intent.action.SEND" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="text/html" />
</intent-filter>
这个是网页。
2.接下来就是接收数据了
在起始的activity中做下面的处理。
Intent itnIn=getIntent();
Bundle extras = itnIn.getExtras();
String action = itnIn.getAction();
if (Intent.ACTION_SEND.equals(action)) {
if (extras.containsKey(Intent.EXTRA_STREAM)) {
try {
// Get resource path from intent
Uri uri2 = (Uri) extras.getParcelable(Intent.EXTRA_STREAM);
// 返回路径
String path = getRealPathFromURI(Activity_Logo_View.this, uri2);
} catch (Exception e) {
Log.e(this.getClass().getName(), e.toString());
}
/**
* 通过Uri获取文件在本地存储的真实路径
* @param act
* @param contentUri
* @return
*/
public String getRealPathFromURI(Activity act, Uri contentUri)
{
// can post image
String[] proj = { MediaStore.Images.Media.DATA };
Cursor cursor = act.managedQuery(contentUri, proj, // Which columns to return
null, // WHERE clause; which rows to return (all rows)
null, // WHERE clause selection arguments (none)
null); // Order-by clause (ascending by name)
if (cursor==null) {
String path = contentUri.getPath();
return path;
}
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
path 就是我们需要的文件路径了,有了它你就能做其他的处理了。