📌  相关文章
📜  如何在 Android 中的活动之间使用 Intent 传递视频?

📅  最后修改于: 2022-05-13 01:54:55.373000             🧑  作者: Mango

如何在 Android 中的活动之间使用 Intent 传递视频?

在 android 中,Intent 提供了一种工具,用于在不同应用程序中的代码之间执行后期运行时绑定。它最重要的用途是在活动的启动中,它可以被认为是活动之间的粘合剂。它基本上是一种被动数据结构,包含对要执行的操作的抽象描述。

我们将在本文中构建什么?

在本文中,我们将学习如何使用 Intent 在两个活动之间传递视频,然后在第二个活动中播放该视频。这是我们将在此应用程序中构建的示例视频。请注意,我们将使用Java语言来实现这个应用程序。

分步实施

第 1 步:创建一个新项目

  • 打开一个新项目。
  • 我们将使用Java语言开发 Empty Activity。保持所有其他选项不变。
  • 您可以在方便时更改项目的名称。
  • 将有两个名为activity_main.xmlMainActivity 的默认文件。Java

如果您不知道如何在 Android Studio 中创建新项目,可以参考如何在 Android Studio 中创建/启动新项目?

第二步:添加存储权限

按照路径app > manifests > AndroidManifest.xml并将以下代码粘贴到其中。

第 3 步:处理 XML 文件

导航到app > res > layout > activity_main.xml并将以下代码添加到该文件。下面是activity_main.xml文件的代码。

XML


  
   


XML


  
    
  
        
  
    
  


Java
package com.example.videointent;
  
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
  
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
  
public class MainActivity extends AppCompatActivity {
  
    // Initialize variables
    Button btSelect;
  
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
  
        // Assign variable
        btSelect=findViewById(R.id.bt_select);
  
        btSelect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // Check condition
                if(ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED)
                {
                    // When permission is not granted
                    // Request permission
                    ActivityCompat.requestPermissions(MainActivity.this,new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}
                    ,1);
                }
                else
                {
                    // When permission is granted
                    // Create method
                    selectVideo();
                }
            }
        });
  
    }
  
    private void selectVideo() {
        // Initialize intent
        Intent intent=new Intent(Intent.ACTION_PICK);
        // set type
        intent.setType("video/*");
        // start activity result
        startActivityForResult(Intent.createChooser(intent,"Select Video"),100);
    }
  
    @Override
    public void onRequestPermissionsResult(int requestCode,  String[] permissions,  int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        // Check condition
        if(requestCode==1 && grantResults.length > 0 && grantResults[0]
        == PackageManager.PERMISSION_GRANTED)
        {
            // When permission is granted
            // Call method
            selectVideo();
        }
        else
        {
            // When permission is denied
            // Display toast
            Toast.makeText(getApplicationContext()
            ,"Permission denied",Toast.LENGTH_SHORT).show();
        }
    }
  
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // Check condition
        if(requestCode==100 && resultCode==RESULT_OK && data!=null)
        {
            // When result code is okay
            // Initialize uri
            Uri uri=data.getData();
            // Initialize intent
            Intent intent=new Intent(this,MainActivity2.class);
            // Put extra
            intent.putExtra("uri",uri.toString());
            // Start activity
            startActivity(intent);
        }
    }
}


Java
package com.example.videointent;
  
import androidx.appcompat.app.AppCompatActivity;
  
import android.net.Uri;
import android.os.Bundle;
import android.widget.VideoView;
  
public class MainActivity2 extends AppCompatActivity {
  
    // Initialize variables
    VideoView videoView;
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
  
        // Assign variables
        videoView=findViewById(R.id.video_view);
        // Get data from main activity
        Bundle bundle=getIntent().getExtras();
        // Check condition
        if(bundle!=null)
        {
            // When bundle not equal to null
            // Initialize uri
            Uri uri=Uri.parse(bundle.getString("uri"));
            // Set video uri
            videoView.setVideoURI(uri);
            // Start video
            videoView.start();
        }
  
    }
}


按照路径应用 > 右键单击 > 新建 > 活动 > 空活动 > 将其命名为“MainActvity2” 。导航到app > res > layout > activity_main2.xml并将以下代码添加到该文件。下面是activity_main2.xml文件的代码。

XML



  
    
  
        
  
    
  

第 4 步:处理Java文件

转到MainActivity。 Java文件并参考以下代码。下面是 MainActivity 的代码。 Java文件。代码中添加了注释以更详细地理解代码。

Java

package com.example.videointent;
  
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
  
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
  
public class MainActivity extends AppCompatActivity {
  
    // Initialize variables
    Button btSelect;
  
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
  
        // Assign variable
        btSelect=findViewById(R.id.bt_select);
  
        btSelect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // Check condition
                if(ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED)
                {
                    // When permission is not granted
                    // Request permission
                    ActivityCompat.requestPermissions(MainActivity.this,new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}
                    ,1);
                }
                else
                {
                    // When permission is granted
                    // Create method
                    selectVideo();
                }
            }
        });
  
    }
  
    private void selectVideo() {
        // Initialize intent
        Intent intent=new Intent(Intent.ACTION_PICK);
        // set type
        intent.setType("video/*");
        // start activity result
        startActivityForResult(Intent.createChooser(intent,"Select Video"),100);
    }
  
    @Override
    public void onRequestPermissionsResult(int requestCode,  String[] permissions,  int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        // Check condition
        if(requestCode==1 && grantResults.length > 0 && grantResults[0]
        == PackageManager.PERMISSION_GRANTED)
        {
            // When permission is granted
            // Call method
            selectVideo();
        }
        else
        {
            // When permission is denied
            // Display toast
            Toast.makeText(getApplicationContext()
            ,"Permission denied",Toast.LENGTH_SHORT).show();
        }
    }
  
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // Check condition
        if(requestCode==100 && resultCode==RESULT_OK && data!=null)
        {
            // When result code is okay
            // Initialize uri
            Uri uri=data.getData();
            // Initialize intent
            Intent intent=new Intent(this,MainActivity2.class);
            // Put extra
            intent.putExtra("uri",uri.toString());
            // Start activity
            startActivity(intent);
        }
    }
}

转到MainActivity2。 Java文件并参考以下代码。下面是 MainActivity2 的代码。 Java文件。代码中添加了注释以更详细地理解代码。

Java

package com.example.videointent;
  
import androidx.appcompat.app.AppCompatActivity;
  
import android.net.Uri;
import android.os.Bundle;
import android.widget.VideoView;
  
public class MainActivity2 extends AppCompatActivity {
  
    // Initialize variables
    VideoView videoView;
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
  
        // Assign variables
        videoView=findViewById(R.id.video_view);
        // Get data from main activity
        Bundle bundle=getIntent().getExtras();
        // Check condition
        if(bundle!=null)
        {
            // When bundle not equal to null
            // Initialize uri
            Uri uri=Uri.parse(bundle.getString("uri"));
            // Set video uri
            videoView.setVideoURI(uri);
            // Start video
            videoView.start();
        }
  
    }
}

这是我们应用程序的最终输出。

输出: