使用android中的fabric lib在twitter上发布图像和视频

时间:2015-06-22 12:51:49

标签: android twitter twitter-fabric

我成功发布了推文(文字),但无法发布图片和视频。

我的PostActivity.java

  public class PostActivity extends Activity implements View.OnClickListener{

    TwitterApiClient twitterApiClient;

    private EditText mShareEditText;
    private TextView userName;
    private ImageView imgPreview;
    private VideoView videoPreview;
    private Button btn_tweet, btn_capture;
    private ProgressDialog pDialog;

    private static final int CAMERA_CAPTURE_IMAGE_REQUEST_CODE = 100;
    private static final int CAMERA_CAPTURE_VIDEO_REQUEST_CODE = 200;
    public static final int MEDIA_TYPE_IMAGE = 1;
    public static final int MEDIA_TYPE_VIDEO = 2;
    private Uri fileUri;
    private static final String IMAGE_DIRECTORY_NAME = "Hello Twitter";
    static File mediaFile;
    static File mediaStorageDir;

    TypedFile typedFile;
    TwitterSession session;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_post);

        mShareEditText = (EditText) findViewById(R.id.share_text);
        userName = (TextView) findViewById(R.id.user_name);
        imgPreview = (ImageView)findViewById(R.id.imageView);
        videoPreview = (VideoView) findViewById(R.id.videoPreview);
        /* register button click listeners */
        btn_tweet = (Button)findViewById(R.id.btn_tweet);
        btn_tweet.setOnClickListener(this);
        btn_capture = (Button)findViewById(R.id.btn_Capture);
        btn_capture.setOnClickListener(this);


        session = Twitter.getSessionManager()
                .getActiveSession();
        twitterApiClient = TwitterCore.getInstance().getApiClient(session);

    }
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btn_tweet:
                getTwitterData(session);

                break;
            case R.id.btn_Capture:
                selectImage();
                break;

        }
    }
    public void getTwitterData(final TwitterSession session) {

        typedFile = new TypedFile("image/jpeg", mediaFile);
        MyTwitterApiClient tapiclient = new MyTwitterApiClient(session);
        tapiclient.getCustomService().upload(typedFile, new Callback<TwitterMedia>() {
            @Override
            public void success(Result<TwitterMedia> result) {
                Toast.makeText(getApplicationContext(),"upload image",Toast.LENGTH_LONG).show();
            }

            @Override
            public void failure(TwitterException e) {

            }
        });
        tweet();
    }


    public void tweet() {


    String strMessage = mShareEditText.getText().toString();

        StatusesService statusesService = twitterApiClient.getStatusesService();
        statusesService.update(strMessage, null, null, null, null, null, null, null, new Callback<Tweet>() {
            @Override
            public void success(Result<Tweet> tweetResult) {
                Toast.makeText(getApplicationContext(),"Successfully Post on twitter",Toast.LENGTH_LONG).show();
            }

            @Override
            public void failure(TwitterException e) {
                e.printStackTrace();
            }
        });
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == CAMERA_CAPTURE_IMAGE_REQUEST_CODE) {
            if (resultCode == RESULT_OK) {
                // successfully captured the image
                // display it in image view
                previewCapturedImage();
            } else if (resultCode == RESULT_CANCELED) {
                // user cancelled Image capture
                Toast.makeText(getApplicationContext(),
                        "User cancelled image capture", Toast.LENGTH_SHORT)
                        .show();
            } else {
                // failed to capture image
                Toast.makeText(getApplicationContext(),
                        "Sorry! Failed to capture image", Toast.LENGTH_SHORT)
                        .show();
            }
        } else if (requestCode == CAMERA_CAPTURE_VIDEO_REQUEST_CODE) {
            if (resultCode == RESULT_OK) {
                // video successfully recorded
                // preview the recorded video
                previewVideo();
            } else if (resultCode == RESULT_CANCELED) {
                // user cancelled recording
                Toast.makeText(getApplicationContext(),
                        "User cancelled video recording", Toast.LENGTH_SHORT)
                        .show();
            } else {
                // failed to record video
                Toast.makeText(getApplicationContext(),
                        "Sorry! Failed to record video", Toast.LENGTH_SHORT)
                        .show();
            }
        }

        super.onActivityResult(requestCode, resultCode, data);
    }


    /**
     * Here we store the file url as it will be null after returning from camera
     * app
     */
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);

        // save file url in bundle as it will be null on scren orientation
        // changes
        outState.putParcelable("file_uri", fileUri);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);

        // get the file url
        fileUri = savedInstanceState.getParcelable("file_uri");
    }

    /**
     * Display image from a path to ImageView
     */
    private void previewCapturedImage() {
        try {
            // hide video preview
            videoPreview.setVisibility(View.GONE);

            imgPreview.setVisibility(View.VISIBLE);

            // bimatp factory
            BitmapFactory.Options options = new BitmapFactory.Options();

            // downsizing image as it throws OutOfMemory Exception for larger
            // images
            options.inSampleSize = 8;

            final Bitmap bitmap = BitmapFactory.decodeFile(fileUri.getPath(),options);

            imgPreview.setImageBitmap(bitmap);
        } catch (NullPointerException e) {
            e.printStackTrace();
        }
    }

    /**
     * Previewing recorded video
     */
    private void previewVideo() {
        try {
            // hide image preview
            imgPreview.setVisibility(View.GONE);

            videoPreview.setVisibility(View.VISIBLE);
            videoPreview.setVideoPath(fileUri.getPath());
            // start playing
            videoPreview.start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * Creating file uri to store image/video
     */
    public Uri getOutputMediaFileUri(int type) {
        return Uri.fromFile(getOutputMediaFile(type));
    }

    /**
     * returning image / video
     */
    public static File getOutputMediaFile(int type){

        // External sdcard location
        mediaStorageDir = new File(
                Environment
                        .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
                IMAGE_DIRECTORY_NAME);


        if (!mediaStorageDir.exists()) {
            if (!mediaStorageDir.mkdirs()) {
                Log.d(IMAGE_DIRECTORY_NAME, "Oops! Failed create "
                        + IMAGE_DIRECTORY_NAME + " directory");
                return null;
            }
        }


        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
                Locale.getDefault()).format(new Date());

        if (type == MEDIA_TYPE_IMAGE) {
            mediaFile = new File(mediaStorageDir.getPath() + File.separator
                    + "IMG_" + timeStamp + ".jpg");
        } else if (type == MEDIA_TYPE_VIDEO) {
            mediaFile = new File(mediaStorageDir.getPath() + File.separator
                    + "VID_" + timeStamp + ".mp4");
        } else {
            return null;
        }

        return mediaFile;
    }

    private void selectImage() {

        final CharSequence[] options = { "Take Photo", "Tack Video","Cancel" };

        AlertDialog.Builder builder = new AlertDialog.Builder(PostActivity.this);
        builder.setTitle("Add Photo!");
        builder.setItems(options, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int item) {
                if (options[item].equals("Take Photo")) {
                    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

                    fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);

                    intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);

                    startActivityForResult(intent, CAMERA_CAPTURE_IMAGE_REQUEST_CODE);
                } else if (options[item].equals("Tack Video")) {
                    Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);

                    fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO);


                    intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);

                    intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); // set the image file

                    startActivityForResult(intent, CAMERA_CAPTURE_VIDEO_REQUEST_CODE);

                } else if (options[item].equals("Cancel")) {
                    dialog.dismiss();
                }
            }
        });
        builder.show();
    }
 }

我使用相机(捕捉)在imageview和videoview上显示图像和视频。

请帮助我 提前谢谢

2 个答案:

答案 0 :(得分:1)

请检查使用Fabric

上传图片

Fabric Compose Tweet

答案 1 :(得分:0)

您的代码缺少部分。您是否可以添加<link href="http://cdn.kendostatic.com/2015.2.624/styles/kendo.material.min.css" rel="stylesheet" /> <link href="http://cdn.kendostatic.com/2015.2.624/styles/kendo.common-material.min.css" rel="stylesheet" /> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="http://cdn.kendostatic.com/2015.2.624/js/kendo.all.min.js"></script> <div id="grid"></div>课程并查看媒体上传内容:http://twitter4j.org/en/index.html