2011-08-02 6 views

답변

25

예, 가능합니다. 노력하고 연구하는 2 일 후에, 나는 그것을 할 수 있었다. fbRequestListener()AsyncFacebookRunner.RequestListener()readBytes()의 구현입니다

byte[] data = null; 
String dataPath = "/mnt/sdcard/KaraokeVideos/myvideo.3gp"; 
String dataMsg = "Your video description here."; 
Bundle param; 
facebook = new Facebook(FB_APP_ID); 
AsyncFacebookRunner mAsyncRunner = new AsyncFacebookRunner(facebook); 
InputStream is = null; 
try { 
    is = new FileInputStream(dataPath); 
    data = readBytes(is); 
    param = new Bundle(); 
    param.putString("message", dataMsg); 
    param.putString("filename", dataName); 
    param.putByteArray("video", data); 
    mAsyncRunner.request("me/videos", param, "POST", new fbRequestListener(), null); 
} 
catch (FileNotFoundException e) { 
    e.printStackTrace(); 
} 
catch (IOException e) { 
    e.printStackTrace(); 
} 

byte[]에 비디오 파일을 변환하는 기능입니다 : 여기에 코드입니다. dataName 문자열에는 유효한 파일 확장명 (3gp, mp4 등)이 포함되어야합니다. 코드는 다음과 같습니다 :

public byte[] readBytes(InputStream inputStream) throws IOException { 
    // This dynamically extends to take the bytes you read. 
    ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream(); 

    // This is storage overwritten on each iteration with bytes. 
    int bufferSize = 1024; 
    byte[] buffer = new byte[bufferSize]; 

    // We need to know how may bytes were read to write them to the byteBuffer. 
    int len = 0; 
    while ((len = inputStream.read(buffer)) != -1) { 
     byteBuffer.write(buffer, 0, len); 
    } 

    // And then we can return your byte array. 
    return byteBuffer.toByteArray(); 
} 

이 코드는 answer에서 가져 왔습니다.

물론 최신 Facebook SDK가 있어야하지만이 patch을 적용하여 {"error":{"type":"OAuthException","message":"(#352) Video file format is not supported"}} 문자열 응답 오류를 수정해야합니다.

그리고 그게 전부입니다! 이게 도움이 되길 바란다!

+0

안녕하세요 저는 게시 한 답변을 사용했습니다. 잘 작동하지만 오류가 발생했습니다. { "type": "OAuthException", "message": "(# 352) Video file format is not supported"}}. 이 오류를 해결하기위한 최신 패치를 제공했습니다.그래서 내가 util 클래스에서 코드를 변경해야한다고 말해주십시오. – Ramakrishna

+0

Util 클래스의 코드를 변경해야한다는 것을 알려주십시오. – Ramakrishna

+0

비디오 파일 이름에 대한 추가 매개 변수를 포함하도록 답변을 편집했습니다. 또한 Util 클래스에 적용해야 할 패치는 다음 링크에서 찾을 수 있습니다. [patch_link] (https://github.com/johnmph/facebook-android-sdk/commit/d0e6ca9d3ecfbe964e72803fdd340cfeafa6ee2e) – Erick

1

Util 파일을 패치 한 후 결과를 얻지 못했습니다.

나는 부드러운 문제에 직면했다.

나는 (페이스 북이 데이터 새로 고침했다가 될 수 있습니다 ..) .. 비디오 (1 분 이내) 언젠가 한 후 내 벽에 표시 .. 이제 성공적으로 작동합니다 ... 안드로이드에서이 함께 노력

String path="\mnt\sdcard\test.mp4"; 

    if (new File(path).exists()) { 
     try { 
      byte[] data = null; 
      String dataPath = new File(path).getAbsolutePath(); 
      Log.e("", dataPath); 
      String dataMsg = "It is the short movie created"; 
      Bundle param; 
      InputStream is = null; 
      try { 
       is = new FileInputStream(dataPath); 
       data = readBytes(is); 
       param = new Bundle(); 
       // param.putString("filename", "" + new 
       // File(path).getName()); 
       // param.putString("mimeType", "video/mp4"); 
       param.putString("message", dataMsg); 
       param.putString("title", "title"); 
       param.putString("contentType", "video/quicktime"); 
       param.putByteArray("video.mov", data); 
       Utility.mAsyncRunner.request("me/videos", param, "POST", 
         new FBRequestListener(), null); 

       Toast.makeText(getContext(), "Uploading...", 
         Toast.LENGTH_SHORT).show(); 
      } catch (FileNotFoundException e) { 
       e.printStackTrace(); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
    } else { 
     Toast.makeText(getContext(), "No videos found in these dates", 
       Toast.LENGTH_SHORT).show(); 
    } 

FBRequestListener.java

public class FBRequestListener implements RequestListener { 

    @Override 
    public void onComplete(String response, Object state) { 
     Log.e("response", response); 
     // Log.e("state", state.toString()); 
    } 

    @Override 
    public void onIOException(IOException e, Object state) { 
     Log.e("", "onIOException"); 
     e.printStackTrace(); 

    } 

    @Override 
    public void onFileNotFoundException(FileNotFoundException e, 
      Object state) { 
     Log.e("", "onFileNotFoundException"); 
     e.printStackTrace(); 

    } 

    @Override 
    public void onMalformedURLException(MalformedURLException e, 
      Object state) { 
     Log.e("", "onMalformedURLException"); 
     e.printStackTrace(); 
    } 

    @Override 
    public void onFacebookError(FacebookError e, Object state) { 
     Log.e("", "onFacebookError"); 
     e.printStackTrace(); 

    } 

} 
2

새로운 facebook SDK 3.5의 출시로 비디오 업로드가 더욱 쉬워졌습니다. 위 여기 SDK 3.5을 사용하거나하는 경우는 새로운 페이스 북 SDK의 버전에서는 페이스 북

//Path to the video, Ex: path = Environment.getExternalStorageDirectory() + File.separator + "myVideo.mp4"; 
     String path; 
     //get the current active facebook session 
     Session session = Session.getActiveSession(); 
     //If the session is open 
     if(session.isOpened()) { 
      //Get the list of permissions associated with the session 
      List<String> permissions = session.getPermissions(); 
      //if the session does not have video_upload permission 
      if(!permissions.contains("video_upload")) { 
       //Get the permission from user to upload the video to facebook 
       Session.NewPermissionsRequest newPermissionsRequest = new Session 
         .NewPermissionsRequest(this, Arrays.asList("video_upload")); 
       session.requestNewReadPermissions(newPermissionsRequest); 
      } 


      //Create a new file for the video 
      File file = new File(path); 
      try { 
       //create a new request to upload video to the facebook 
       Request videoRequest = Request.newUploadVideoRequest(session, file, new Request.Callback() { 

        @Override 
        public void onCompleted(Response response) { 

         if(response.getError()==null) 
         { 
          Toast.makeText(MainActivity.this, "video shared successfully", Toast.LENGTH_SHORT).show(); 
         } 
         else 
         { 
          Toast.makeText(MainActivity.this, response.getError().getErrorMessage(), Toast.LENGTH_SHORT).show(); 
         } 
        } 
       }); 

       //Execute the request in a separate thread 
       videoRequest.executeAsync(); 

      } catch (FileNotFoundException e) { 
       e.printStackTrace(); 
      } 
     } 

     //Session is not open 
     else { 
      Toast.makeText(getApplicationContext(), "Please login to facebook first", Toast.LENGTH_SHORT).show(); 
     } 
+0

이 동영상은 저 또한 효과적입니다.하지만 동영상에 제목을 어떻게 추가 할 수 있습니까? –

1

에 비디오를 업로드 코드입니다, 페이스 북 페이지 나 벽에 비디오 업로드에 약간의 변화가있다.

여기는 페이스 북 페이지 또는 페이스 북 벽에 비디오를 업로드하는 데 사용한 코드입니다.

귀하의 onActivityResult() 방법은 다음이

@Override 
protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
    super.onActivityResult(requestCode, resultCode, data); 
    if(requestCode == CAMERA_VIDEO && resultCode == Activity.RESULT_OK){ 
     String selectedVideoFilePath = GetFilePathFromDevice.getPath(this, data.getData()); 
     final byte[] datas = readBytes(selectedVideoFilePath); 
     PostVideo(datas, selectedVideoFilePath); 
    } 
} 

처럼해야 할 것은 다음 URI에서 파일 경로를 얻기 위해 onActivityResult()에 사용 GetFilePathFromDevice 클래스는 onActivityResult().

public byte[] readBytes(String dataPath) throws IOException { 
     InputStream inputStream = new FileInputStream(dataPath); 
     ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream(); 
     byte[] buffer = new byte[1024]; 
     int len; 
     while ((len = inputStream.read(buffer)) != -1) { 
      byteBuffer.write(buffer, 0, len); 
     } 
     return byteBuffer.toByteArray(); 
} 


public void PostVideo(byte[] VideoBytes, String filePath) { 
     String url; 
     url = "/me/videos"; 

     AccessToken token = AccessToken.getCurrentAccessToken(); 
     if (token != null) { 
      Bundle param = new Bundle(); 
      param.putByteArray("video." + getFileExt(filePath), VideoBytes); 
      param.putString("description", "sample video"); 
      new GraphRequest(token,url, param, HttpMethod.POST, new GraphRequest.Callback() { 

       public void onCompleted(GraphResponse response) { 
        Log.e("New Post", "Res =" + response.toString()); 
        dialog.dismiss(); 

        if (response != null && response.getJSONObject() != null && response.getJSONObject().has("id")) { 
         Log.e("New Post", "Success"); 
         Toast.makeText(NewPostActivity.this, "Video posted successfully.", Toast.LENGTH_SHORT).show(); 
        } else { 
         Toast.makeText(NewPostActivity.this, "Error in posting Video.", Toast.LENGTH_SHORT).show(); 
        } 
        setResult(Activity.RESULT_OK, new Intent()); 
        finish(); 
       } 
      }).executeAsync(); 
     } 
} 

public static String getFileExt(String fileName) { 
     return fileName.substring((fileName.lastIndexOf(".") + 1), fileName.length()); 
} 

에 사용되는 모든 방법입니다.

@SuppressLint("NewApi") 
public final class GetFilePathFromDevice { 

/** 
* Get file path from URI 
* 
* @param context context of Activity 
* @param uri  uri of file 
* @return path of given URI 
*/ 
public static String getPath(final Context context, final Uri uri) { 
    final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT; 
    // DocumentProvider 
    if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) { 
     // ExternalStorageProvider 
     if (isExternalStorageDocument(uri)) { 
      final String docId = DocumentsContract.getDocumentId(uri); 
      final String[] split = docId.split(":"); 
      final String type = split[0]; 
      if ("primary".equalsIgnoreCase(type)) { 
       return Environment.getExternalStorageDirectory() + "/" + split[1]; 
      } 
     } 
     // DownloadsProvider 
     else if (isDownloadsDocument(uri)) { 
      final String id = DocumentsContract.getDocumentId(uri); 
      final Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(id)); 
      return getDataColumn(context, contentUri, null, null); 
     } 
     // MediaProvider 
     else if (isMediaDocument(uri)) { 
      final String docId = DocumentsContract.getDocumentId(uri); 
      final String[] split = docId.split(":"); 
      final String type = split[0]; 
      Uri contentUri = null; 
      if ("image".equals(type)) { 
       contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI; 
      } else if ("video".equals(type)) { 
       contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI; 
      } else if ("audio".equals(type)) { 
       contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI; 
      } 
      final String selection = "_id=?"; 
      final String[] selectionArgs = new String[]{split[1]}; 
      return getDataColumn(context, contentUri, selection, selectionArgs); 
     } 
    } 
    // MediaStore (and general) 
    else if ("content".equalsIgnoreCase(uri.getScheme())) { 
     // Return the remote address 
     if (isGooglePhotosUri(uri)) 
      return uri.getLastPathSegment(); 
     return getDataColumn(context, uri, null, null); 
    } 
    // File 
    else if ("file".equalsIgnoreCase(uri.getScheme())) { 
     return uri.getPath(); 
    } 
    return null; 
} 

public static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) { 
    Cursor cursor = null; 
    final String column = "_data"; 
    final String[] projection = {column}; 
    try { 
     cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null); 
     if (cursor != null && cursor.moveToFirst()) { 
      final int index = cursor.getColumnIndexOrThrow(column); 
      return cursor.getString(index); 
     } 
    } finally { 
     if (cursor != null) 
      cursor.close(); 
    } 
    return null; 
} 

public static boolean isExternalStorageDocument(Uri uri) { 
    return "com.android.externalstorage.documents".equals(uri.getAuthority()); 
} 

public static boolean isDownloadsDocument(Uri uri) { 
    return "com.android.providers.downloads.documents".equals(uri.getAuthority()); 
} 

public static boolean isMediaDocument(Uri uri) { 
    return "com.android.providers.media.documents".equals(uri.getAuthority()); 
} 

public static boolean isGooglePhotosUri(Uri uri) { 
    return "com.google.android.apps.photos.content".equals(uri.getAuthority()); 
} 
} 
관련 문제