【发布时间】:2014-09-23 18:01:46
【问题描述】:
我正在尝试通过内容提供商在单独的应用程序中传回图像。我有两个应用程序,一个具有(应用程序 a)中的活动,另一个具有内容提供程序(应用程序 b)
我的应用 a 使用以下代码通过应用 b 从我的 SD 卡中读取图像。
应用程序:
public void but_update(View view)
{
ContentResolver resolver = getContentResolver();
Uri uri = Uri.parse("content://com.jash.cp_source_two.provider/note/1");
InputStream inStream = null;
try
{
inStream = resolver.openInputStream(uri);
Bitmap bitmap = BitmapFactory.decodeStream(inStream);
image = (ImageView) findViewById(R.id.imageView1);
image.setImageBitmap(bitmap);
}
catch(FileNotFoundException e)
{
Toast.makeText(getBaseContext(), "error = "+e, Toast.LENGTH_LONG).show();
}
finally {
if (inStream != null) {
try {
inStream.close();
} catch (IOException e) {
Log.e("test", "could not close stream", e);
}
}
}
};
应用程序 b:
@Override
public ParcelFileDescriptor openFile(Uri uri, String mode)
throws FileNotFoundException {
try
{
File path = new File(Environment.getExternalStorageDirectory().getAbsolutePath(),"pic2.png");
return ParcelFileDescriptor.open(path,ParcelFileDescriptor.MODE_READ_ONLY);
}
catch (FileNotFoundException e)
{
Log.i("r", "File not found");
throw new FileNotFoundException();
}
}
在应用程序 a 中,我可以显示应用程序 a 的资源文件夹中的图像,使用 setImageURi 并使用以下代码构造 URI。
int id = R.drawable.a2;
Resources resources = getBaseContext().getResources();
Uri uri = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" +
resources.getResourcePackageName(id) + '/' +
resources.getResourceTypeName(id) + '/' +
resources.getResourceEntryName(id) );
image = (ImageView) findViewById(R.id.imageView1);
image.setImageURI(uri);
但是,如果我尝试在应用程序 b 中执行相同操作(从应用程序 b 的资源文件夹而不是 SD 卡上的图像读取)它不起作用,说它找不到文件,即使我是从资源创建文件的路径,所以它肯定存在。
有什么想法吗?它是否以某种方式限制通过内容提供者发送资源?
附:当我尝试使用
创建文件时,我也遇到了错误File path = new File(uri); 说'没有适用于'(android.net.Uri)'的构造函数虽然http://developer.android.com/reference/java/io/File.html#File(java.net.URI) 似乎认为这是可能的......除非java.net.URI 与android.net.URI 不同,在这种情况下可以我转换它们?
谢谢
罗斯
【问题讨论】:
标签: android android-contentprovider android-resources