从Android中的sdcard中选择PDF

时间:2014-06-03 07:19:27

标签: android

我想从sdcard中选择PDF文件,然后在我的android项目中上传到服务器。请帮我这样做。如果可能的话请告诉我这样做的代码。我还尝试使用视频选择示例代码,但它显示" 没有应用程序可以执行此操作"。 enter code here

Button b1;
private static final int SELECT_VIDEO_DIALOG = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    b1=(Button)findViewById(R.id.button1);

    b1.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            Intent intent = new Intent();
            intent.setType("pdf/*");
            intent.setAction(Intent.ACTION_GET_CONTENT);
            startActivityForResult(Intent.createChooser(intent, "Select Video"), SELECT_VIDEO_DIALOG);
        }
    });
}

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

    if (resultCode == RESULT_OK)
    {
        if (requestCode == SELECT_VIDEO_DIALOG)
        {
            System.out.println("SELECT_VIDEO");
            Uri selectedImageUri = data.getData();
            String selectedpath = getPath(selectedImageUri);
            System.out.println("SELECT_VIDEO Path : " + selectedpath);
        }
    }
}

private String getPath(Uri uri) {
    String[] projection = { MediaStore.Video.Media.DATA, MediaStore.Video.Media.SIZE, MediaStore.Video.Media.DURATION}; 
    @SuppressWarnings("deprecation")
    Cursor cursor = managedQuery(uri, projection, null, null, null);
    cursor.moveToFirst(); 
    String filePath = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATA));
    int fileSize = cursor.getInt(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.SIZE));
    long duration = TimeUnit.MILLISECONDS.toSeconds(cursor.getInt(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DURATION)));
    //some extra potentially useful data to help with filtering if necessary
    System.out.println("size: " + fileSize);
    System.out.println("path: " + filePath);
    System.out.println("duration: " + duration);

    return filePath;
}

1 个答案:

答案 0 :(得分:0)

嗨,如果你想要列出文件而不是你可以使用

    Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
    intent.setType("file/*");
    startActivityForResult(intent, YOUR_RESULT_CODE);

如果您只想要PDF文件,请点击此链接https://stackoverflow.com/a/27407812/4741746