访问内部存储和外部 SD 卡中的视频 - Android

问题描述 投票:0回答:2

我开发了一个简单的 Android 应用程序,它将从 path="storage/MicroSD/Videos" 并将它们显示在列表视图中,选择视频后,将播放所选视频。播放位于存储/MicroSD/视频中的视频。但其他路径中的视频不会被获取。请给出一些想法,如何从所有路径(内部存储和外部存储)获取视频。此外,如果我在不同的手机上运行相同的应用程序,SD 卡路径会有所不同,如

Storage/SD Card o/videos
。 现在是我的问题:如何以编程方式获得指向任何设备的默认视频目录的
File
对象?

主要活动

    public class MainActivity extends Activity {

    private ListView mListView;
    private List<String> fileNameList;
    public  String path="storage/MicroSD/Videos";
    private File file;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    file = Environment.getExternalStorageDirectory();
    fileNameList = getFileListfromSDCard();
    final ListView listView = (ListView) findViewById(R.id.list);
    ArrayAdapter<String> adapter1 = new ArrayAdapter<String> (this,android.R.layout.simple_list_item_1, android.R.id.text1, fileNameList);
    listView.setAdapter(adapter1);
    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                                int position, long id) {
            int itemPosition = position;
            String itemValue = (String)   listView.getItemAtPosition(position);
            Intent intent = new Intent(MainActivity.this, com.video.videolibrary.SelectedVideo.class);
            intent.putExtra("id", id);
            intent.putExtra("itemValue", itemValue);
            intent.putExtra("path", path);
            startActivity(intent);
        }

        });

    Button button = (Button) findViewById(R.id.btn_Online);
    // Capture button clicks
    button.setOnClickListener(new OnClickListener() {
        public void onClick(View arg0) {
           Intent myIntent = new Intent(MainActivity.this,com.video.videolibrary.SelectedVideo.class);
            startActivity(myIntent);
        }
    });

    }

    private List<String> getFileListfromSDCard() {

    File files = new File(path);
    FileFilter filter = new FileFilter() {
        private final List<String> exts = Arrays.asList("mp4","MP4");
        @Override
        public boolean accept(File pathname) {
            String ext;
            String path = pathname.getPath();
            ext = path.substring(path.lastIndexOf(".") + 1);
            return exts.contains(ext);
        }
    };

    final File [] filesFound = files.listFiles(filter);
    List<String> flLst = new ArrayList<String>();
    if (filesFound != null && filesFound.length > 0) {
        for (File file : filesFound) {
            flLst.add(file.getName());
         }
    }
    return flLst;
    }

    }

所选视频课程

        public class SelectedVideo extends Activity {
        VideoView view;AudioManager audioManager;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.selected_video);
        view = (VideoView)findViewById(R.id.videoView1);
       Bundle bundle = getIntent().getExtras();
       String path=bundle.getString("path");
       String itemValue = bundle.getString("itemValue");
      view.setVideoURI(Uri.parse(path+"/"+itemValue ));
      VideoView videoView = (VideoView) findViewById(R.id.videoView1);
      MediaController mediaController = new MediaController(this);
      mediaController.setAnchorView(videoView);
      Uri uri = Uri.parse(path+"/"+itemValue);
      DisplayMetrics dm = new DisplayMetrics();
      this.getWindowManager().getDefaultDisplay().getMetrics(dm);
      int height = dm.heightPixels;
      int width = dm.widthPixels;
     videoView.setMinimumWidth(width);
     videoView.setMinimumHeight(height);
     videoView.setMediaController(mediaController);
     videoView.setVideoURI(uri);
     videoView.requestFocus();
     audioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
     int maxVolume =    audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
     int curVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
     SeekBar volControl = (SeekBar)findViewById(R.id.volbar);
     volControl.setMax(maxVolume);
     volControl.setProgress(curVolume);
     volControl.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {

        @Override
        public void onStopTrackingTouch(SeekBar arg0) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onStartTrackingTouch(SeekBar arg0) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onProgressChanged(SeekBar arg0, int arg1, boolean arg2)    {
            // TODO Auto-generated method stub
            audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, arg1, 0);
        }
        });

        Button stopbutton = (Button) findViewById(R.id.btn_stop);
        stopbutton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            view.pause();

            }
        });

        Button playbutton = (Button) findViewById(R.id.btn_play);
        playbutton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            Bundle bundle = getIntent().getExtras();
            String itemValue = bundle.getString("itemValue");
            Toast.makeText(getApplicationContext(),
                    itemValue, Toast.LENGTH_LONG)
                    .show();
            view.start();
        }
        });

        Button backbutton = (Button) findViewById(R.id.btn_back);
        backbutton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
            view.stopPlayback();
            startActivity(new Intent(SelectedVideo.this, MainActivity.class));
            }
        });

        }
        @Override
        public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
    }
    }

Android 清单文件

        <uses-permission android:name="android.permission.INTERNET"/>
        <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
        <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
        <uses-permission android:name="android.permission.read_external_storage" />
        <application
        android:allowBackup="true"
        android:icon="@mipmap/video_library"
        android:label="@string/app_name"
        android:theme="@style/AppTheme"
        android:configChanges="orientation|keyboardHidden">
        <activity
        android:name="com.video.videolibrary.MainActivity"
        android:label="@string/app_name">

        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
        </activity>
        <activity
        android:name=".SelectedVideo">
        </activity>
        </application>

        </manifest>
android storage android-videoview
2个回答
0
投票

首先:不要硬编码 SD 卡的路径。您应该使用

getExternalStorageDirectory ()
来获取指向此位置的
File
对象。所以你的变量
files
应该被分配如下:

File files= Environment.getExternalStorageDirectory(Environment.DIRECTORY_MOVIES);

由于这将返回默认位置,用户可以访问的视频将存储在该位置,因此这个位置应该可以满足您的需求。

android api 对此表示:

注意:不要对这里的“外部”一词感到困惑。这个目录 可以更好地将其视为媒体/共享存储。它是一个文件系统 可以容纳相对大量的数据,并且可以在多个系统之间共享 所有应用程序(不强制执行权限)。传统上这是 SD 卡,但也可以作为内置存储器实现 设备与受保护的内部存储不同,并且可以 作为文件系统安装在计算机上。

另一种选择是使用

ContentProvider
。使用光标,您可以查询该光标并获取每个索引视频。这将使您无需明确搜索视频。

基本的

Cursor
查询基本上如下所示:

Cursor cursor=getContentResolver().query(
    MediaStore.Video.Media,              // The content URI of the table
    mProjection,                         // The columns to return for each row
    mSelectionClause,                    // Selection criteria
    null,                                // replacing placeholders of Selection criterias
    mSortOrder);                         // The sort order for the returned rows

    while(cursor.moveToNext()){
     //work with your data here
    }

从 Android-Manifest.xml 中删除此行,这是不必要的:

<uses-permission android:name="android.permission.read_external_storage" />

0
投票

试试这个:

    String path = Environment.getExternalStorageDirectory().toString();
   // String path = "Environment.getExternalStorageDirectory().toString()+"/myvideo";

    ArrayList<String>alPath=new ArrayList<String>();
    ArrayList<String> alName=new ArrayList<String>();

    File directory = new File(path);
    File[] file = directory.listFiles();
    for (int i = 0; i < file.length; i++) {

            alName.add(file[i].getName());
           alPath.add(file[i].getAbsolutePath());


    ArrayAdapter<String> arrayAdapter=new ArrayAdapter<String>
   (VideoList.this,android.R.layout.simple_list_item_1,alName);
    listView.setAdapter(arrayAdapter);
© www.soinside.com 2019 - 2024. All rights reserved.