从URL无法正常创建临时图像

时间:2015-06-18 07:49:23

标签: android json

  • 列表项

我正在使用JSON从URL加载一些图像,并在新活动中以完整大小打开它们 在该活动中,我想使用ShareActionProvider分享它们。

有关Stack Overflow的一些问题建议先将它们作为临时文件下载,但它不能使用我的代码:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_full_screen);

    Intent i = getIntent();
    path = i.getStringExtra(TAG_FILEIMG);

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.full_screen, menu);

    MenuItem item = menu.findItem(R.id.menu_item_share);
    mShareActionProvider = (ShareActionProvider) item.getActionProvider();
    mShareActionProvider.setShareIntent(createShareIntent());

    return true;
}

public File getTempFile(Context context, String url) {

    url = path;
    try {
        String fileName = Uri.parse(url).getLastPathSegment();
        file = File.createTempFile(fileName, null, context.getCacheDir());
    }catch (IOException e) {
        e.printStackTrace();
    }
    return file;

}

private Intent createShareIntent() {
    Intent shareIntent = new Intent(Intent.ACTION_SEND);
    shareIntent.putExtra(Intent.EXTRA_STREAM, file);
    shareIntent.setType("image/*");


    return shareIntent;

}

full_screen.xml

<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
tools:context="com.habitodigital.FullScreenActivity" >

    <item
    android:id="@+id/menu_item_share"
    android:showAsAction="ifRoom"
    android:title="@string/share"
    android:actionProviderClass="android.widget.ShareActionProvider"/>

</menu>

path 是我使用ImageLoader加载图片时使用的JSON图像路径。
这个临时文件创建代码是否正确?

1 个答案:

答案 0 :(得分:1)

你在这里创建一个空文件。

public File getTempFile(Context context, String url) {

url = path;
try {
    String fileName = Uri.parse(url).getLastPathSegment();
    file = File.createTempFile(fileName, null, context.getCacheDir());
}catch (IOException e) {
    e.printStackTrace();
}
return file;

}

您应该从网站下载图像并将其写入该文件。

您可以使用FileOutputStream在文件上书写。