【发布时间】:2016-06-15 05:14:26
【问题描述】:
根据 Twitter 文档
使用 Fabric 初始化 TweetComposer Kit 后,使用 Builder 开始构建 Tweet Composer。
import com.twitter.sdk.android.tweetcomposer.TweetComposer;
...
TweetComposer.Builder builder = new TweetComposer.Builder(this)
.text("just setting up my Fabric.")
.image(myImageUri);
builder.show();
图像 Uri 应该是文件 Uri(即 file://absolute_path 方案) 到本地文件。例如,
File myImageFile = new File("/path/to/image");
Uri myImageUri = Uri.fromFile(myImageFile);
问题在于,当共享对话框出现时,会出现一条带有“无法加载图像”消息的 toast。这是我的代码,我在其中使用 Volley 下载图像,然后将图像保存在本地。检查文件是否存在成功但之后图像没有插入到共享对话框中:
更新 正如 Alexander 建议的那样,解决方案是使用 File Provider。这是更新的代码:
public void showShareDialogTwitter(JSONObject response) {
Gson gson = new GsonBuilder().create();
final Advertisement item = gson.fromJson(response.toString(), Advertisement.class);
// ==========================================================================
ImageRequest request = new ImageRequest(item.getImages().get(0), new Response.Listener<Bitmap>() {
public void onResponse(Bitmap response) {
String path = giveThePathToImage(response);
if (path != null && path != "") {
//File myImageFile = new File(path + "/share.jpg");
File file = new File(getFilesDir(), "share.jpg");
if (file.exists()) {
Uri contentUri = FileProvider.getUriForFile(MainActivity.this,
"bg.web3.takeforfree.MainActivity", file);
//Uri myImageUri = Uri.fromFile(myImageFile);
String name;
if (item.getName() != null) {
name = item.getName();
} else {
name = "";
}
TweetComposer.Builder builder = new TweetComposer.Builder(MainActivity.this)
.text(MainActivity.this.getResources().getString(R.string.seeMyAdd) + name).image(contentUri);
builder.show();
}
}
}
}, 400, 400, null, null, new Response.ErrorListener() {
public void onErrorResponse(VolleyError error) {
Log.i("Sharing", "Error");
}
});
Volley.newRequestQueue(this).add(request);
// ==========================================================================
}
private String giveThePathToImage(Bitmap bitmapImage) {
File directory = getFilesDir();
File mypath = new File(directory, "share.jpg");
FileOutputStream fos = null;
try {
fos = new FileOutputStream(mypath);
bitmapImage.compress(Bitmap.CompressFormat.PNG, 100, fos);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return directory.getAbsolutePath();
}
AndroidManifest.xml
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="bg.web3.takeforfree.MainActivity"
android:exported="false"
android:grantUriPermissions="true" >
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths" />
</provider>
file_paths.xml
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<files-path name="my_images" path="."/>
</paths>
【问题讨论】:
标签: android twitter social-networking