找到你要的答案

Q:Post media tweets with Twitter Fabric SDK

Q:后媒体的推推特面料SDK

I have included Twitter Fabric SDK in my android application and can post tweets from it. I would like to post images as well though but that doesn't seem possible through the StatusesService that is used to post text-only tweets.

Is it not possible to do this through the SDK? Do I have to do an explicit http post for this?

我有推特面料SDK我Android应用可以从它后鸣叫。我想后图像以及虽然但似乎并不可能通过statusesservice是用来发布文字只鸣叫。

这是不可能做到这一点通过SDK?我要为这个做一个明确的HTTP POST?

answer1: 回答1:

According to the Fabric SDK, yes you can embed media in your Tweet through TweetUI.

Sample Code

Initialize with Fabric

Fabric.with(this, new TweetComposer());

Tweet Code

TweetComposer.Builder builder = new TweetComposer.Builder(this)
     .text("just setting up my Fabric.")
     .image(myImageUri);

builder.show();

File myImageFile = new File("/path/to/image");
Uri myImageUri = Uri.fromFile(myImageFile);

Remember

In the event that the Twitter app is not installed, TweetComposer will create an intent to interact with the Twitter.com in a browser. The browser ignores a specified image.

根据织物的SDK,你可以在你的鸣叫通过tweetui嵌入媒体。

示例代码

初始化与织物

Fabric.with(this, new TweetComposer());

鸣叫的代码

TweetComposer.Builder builder = new TweetComposer.Builder(this)
     .text("just setting up my Fabric.")
     .image(myImageUri);

builder.show();

File myImageFile = new File("/path/to/image");
Uri myImageUri = Uri.fromFile(myImageFile);

记得

In the event that the Twitter app is not installed, TweetComposer will create an intent to interact with the Twitter.com in a browser. The browser ignores a specified image.

answer2: 回答2:
package ...




public class StatusFragment extends Fragment {
Button btn_select, btn_post_image;
EditText edt_status;
String status;
ImageView img_status;
private static final int RESULT_LOAD_IMAGE = 1;
SharedPreferences mSharedPreferences;
String selectedImagePath;
Uri selectedImage;
TypedFile typedFile;
private static final String IMAGE_DIRECTORY_NAME = "Hello Twitter";
String mCurrentPhotoPath;
File mFile;
ProgressDialog pDialog;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    View rootView = inflater.inflate(R.layout.fragment_status, container, false);
    btn_post_image = (Button) rootView.findViewById(R.id.btn_post_image);
    btn_select = (Button) rootView.findViewById(R.id.btn_select);
    edt_status = (EditText) rootView.findViewById(R.id.edt_status);
    img_status = (ImageView) rootView.findViewById(R.id.img_status);
    btn_post_image.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (StatusFragment.CheckNetwork.isInternetAvailable(getActivity()))  //if connection available
            {
                pDialog = new ProgressDialog(getActivity());
                pDialog.setMessage("Uploading......");
                pDialog.show();
                final TwitterSession session = Twitter.getSessionManager().getActiveSession();
                mFile = new File(getRealPathFromURI(selectedImage));
                TypedFile typedFile = new TypedFile("application/octet-stream", mFile);
                TwitterApiClient twitterApiClient = TwitterCore.getInstance().getApiClient(session);
                MediaService ms = twitterApiClient.getMediaService();
                ms.upload(typedFile, null, null, new Callback<Media>() {

                    @Override
                    public void success(Result<Media> mediaResult) {
                        // show on User Timeline

//                            StatusesService statusesService =    TwitterCore.getInstance().getApiClient(session).getStatusesService();
//                                 statusesService.update(edt_status.getText().toString(), null, false, null, null, null, true, false, mediaResult.data.mediaIdString, new Callback<Tweet>() {
//                                @Override
//                                public void success(Result<Tweet> tweetResult) {
//                                    //...
//                                    Toast.makeText(getActivity(), "Upload Complete", Toast.LENGTH_SHORT).show();
//                                    pDialog.dismiss();
//                                }
//
//                                @Override
//                                public void failure(TwitterException e) {
//                                    //...
//                                    Toast.makeText(getActivity(), "Upload Error" + e.getMessage(), Toast.LENGTH_SHORT).show();
//                                    pDialog.dismiss();
//                                }
//
//                            });

                        // Show on Home Timeline
                        StatusesService statusesService = TwitterCore.getInstance().getApiClient(session).getStatusesService();

                        statusesService.update( " content: " + edt_status.getText().toString(), null, false, null, null, null, true, false, mediaResult.data.mediaIdString, new Callback<Tweet>() {
                            @Override
                            public void success(Result<Tweet> tweetResult) {
                                pDialog.dismiss();
                                Toast.makeText(getActivity(), "Upload Completed", Toast.LENGTH_SHORT).show();
                            }

                            @Override
                            public void failure(TwitterException e) {
                                //...
                                pDialog.dismiss();
                                Toast.makeText(getActivity(), "Upload Error"+e.getMessage(), Toast.LENGTH_SHORT).show();
                            }

                        });


                    }

                    @Override
                    public void failure(TwitterException e) {
                        //...
                        Toast.makeText(getActivity(), e.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                });
            } else{
                Toast.makeText(getActivity(), "Network error", Toast.LENGTH_SHORT).show();
            }
        }


    });


    btn_select.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            startActivityForResult(i, RESULT_LOAD_IMAGE);

        }

    });


    return rootView;
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == RESULT_LOAD_IMAGE && resultCode == Activity.RESULT_OK) {
        selectedImage = data.getData();
        img_status.setImageURI(selectedImage);

    }

}

public Uri getImageUri(Context inContext, Bitmap inImage) {
    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
    String path = MediaStore.Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null);
    return Uri.parse(path);
}

public String getRealPathFromURI(Uri contentUri) {
    try {
        String[] proj = {MediaStore.Images.Media.DATA};
        Cursor cursor = getActivity().managedQuery(contentUri, proj, null, null, null);
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    } catch (Exception e) {
        return contentUri.getPath();
    }
}


public static class CheckNetwork {
    static String TAG = CheckNetwork.class.getSimpleName();

    public static boolean isInternetAvailable(Context context) {
        NetworkInfo info = (NetworkInfo) ((ConnectivityManager)
                context.getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();

        if (info == null) {
            Log.d(TAG, "no internet connection");
            return false;
        } else {
            if (info.isConnected()) {
                Log.d(TAG, " internet connection available...");
                return true;
            } else {
                Log.d(TAG, " internet connection");
                return true;
            }

        }
    }
}

public class MyTwitterApiClient extends TwitterApiClient {

    public MyTwitterApiClient(TwitterSession session) {
        super(session);
    }

    public UploadMediaService getUploadMediaService() {

        return getService(UploadMediaService.class);
    }


}

interface UploadMediaService {

    @Multipart
    @POST("1.1/media/upload.json")
    void upload(@Part("media") TypedFile file, @Part("additional_owners") String owners, Callback<MediaEntity> cb);

}

public void openPath(Uri uri) {
    InputStream is = null;
    try {
        is = getActivity().getContentResolver().openInputStream(uri);
        //Convert your stream to data here
        is.close();

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

}

Try it!

package ...




public class StatusFragment extends Fragment {
Button btn_select, btn_post_image;
EditText edt_status;
String status;
ImageView img_status;
private static final int RESULT_LOAD_IMAGE = 1;
SharedPreferences mSharedPreferences;
String selectedImagePath;
Uri selectedImage;
TypedFile typedFile;
private static final String IMAGE_DIRECTORY_NAME = "Hello Twitter";
String mCurrentPhotoPath;
File mFile;
ProgressDialog pDialog;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    View rootView = inflater.inflate(R.layout.fragment_status, container, false);
    btn_post_image = (Button) rootView.findViewById(R.id.btn_post_image);
    btn_select = (Button) rootView.findViewById(R.id.btn_select);
    edt_status = (EditText) rootView.findViewById(R.id.edt_status);
    img_status = (ImageView) rootView.findViewById(R.id.img_status);
    btn_post_image.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (StatusFragment.CheckNetwork.isInternetAvailable(getActivity()))  //if connection available
            {
                pDialog = new ProgressDialog(getActivity());
                pDialog.setMessage("Uploading......");
                pDialog.show();
                final TwitterSession session = Twitter.getSessionManager().getActiveSession();
                mFile = new File(getRealPathFromURI(selectedImage));
                TypedFile typedFile = new TypedFile("application/octet-stream", mFile);
                TwitterApiClient twitterApiClient = TwitterCore.getInstance().getApiClient(session);
                MediaService ms = twitterApiClient.getMediaService();
                ms.upload(typedFile, null, null, new Callback<Media>() {

                    @Override
                    public void success(Result<Media> mediaResult) {
                        // show on User Timeline

//                            StatusesService statusesService =    TwitterCore.getInstance().getApiClient(session).getStatusesService();
//                                 statusesService.update(edt_status.getText().toString(), null, false, null, null, null, true, false, mediaResult.data.mediaIdString, new Callback<Tweet>() {
//                                @Override
//                                public void success(Result<Tweet> tweetResult) {
//                                    //...
//                                    Toast.makeText(getActivity(), "Upload Complete", Toast.LENGTH_SHORT).show();
//                                    pDialog.dismiss();
//                                }
//
//                                @Override
//                                public void failure(TwitterException e) {
//                                    //...
//                                    Toast.makeText(getActivity(), "Upload Error" + e.getMessage(), Toast.LENGTH_SHORT).show();
//                                    pDialog.dismiss();
//                                }
//
//                            });

                        // Show on Home Timeline
                        StatusesService statusesService = TwitterCore.getInstance().getApiClient(session).getStatusesService();

                        statusesService.update( " content: " + edt_status.getText().toString(), null, false, null, null, null, true, false, mediaResult.data.mediaIdString, new Callback<Tweet>() {
                            @Override
                            public void success(Result<Tweet> tweetResult) {
                                pDialog.dismiss();
                                Toast.makeText(getActivity(), "Upload Completed", Toast.LENGTH_SHORT).show();
                            }

                            @Override
                            public void failure(TwitterException e) {
                                //...
                                pDialog.dismiss();
                                Toast.makeText(getActivity(), "Upload Error"+e.getMessage(), Toast.LENGTH_SHORT).show();
                            }

                        });


                    }

                    @Override
                    public void failure(TwitterException e) {
                        //...
                        Toast.makeText(getActivity(), e.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                });
            } else{
                Toast.makeText(getActivity(), "Network error", Toast.LENGTH_SHORT).show();
            }
        }


    });


    btn_select.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            startActivityForResult(i, RESULT_LOAD_IMAGE);

        }

    });


    return rootView;
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == RESULT_LOAD_IMAGE && resultCode == Activity.RESULT_OK) {
        selectedImage = data.getData();
        img_status.setImageURI(selectedImage);

    }

}

public Uri getImageUri(Context inContext, Bitmap inImage) {
    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
    String path = MediaStore.Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null);
    return Uri.parse(path);
}

public String getRealPathFromURI(Uri contentUri) {
    try {
        String[] proj = {MediaStore.Images.Media.DATA};
        Cursor cursor = getActivity().managedQuery(contentUri, proj, null, null, null);
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    } catch (Exception e) {
        return contentUri.getPath();
    }
}


public static class CheckNetwork {
    static String TAG = CheckNetwork.class.getSimpleName();

    public static boolean isInternetAvailable(Context context) {
        NetworkInfo info = (NetworkInfo) ((ConnectivityManager)
                context.getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();

        if (info == null) {
            Log.d(TAG, "no internet connection");
            return false;
        } else {
            if (info.isConnected()) {
                Log.d(TAG, " internet connection available...");
                return true;
            } else {
                Log.d(TAG, " internet connection");
                return true;
            }

        }
    }
}

public class MyTwitterApiClient extends TwitterApiClient {

    public MyTwitterApiClient(TwitterSession session) {
        super(session);
    }

    public UploadMediaService getUploadMediaService() {

        return getService(UploadMediaService.class);
    }


}

interface UploadMediaService {

    @Multipart
    @POST("1.1/media/upload.json")
    void upload(@Part("media") TypedFile file, @Part("additional_owners") String owners, Callback<MediaEntity> cb);

}

public void openPath(Uri uri) {
    InputStream is = null;
    try {
        is = getActivity().getContentResolver().openInputStream(uri);
        //Convert your stream to data here
        is.close();

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

}

试试!

android  twitter  media  fabric-twitter