Как запустить фоновое видео в активности Android? - PullRequest
0 голосов
/ 12 июня 2019

Я хочу внедрить фоновое видео в основной вид деятельности моего приложения.Первоначально я пытался добавить это видео как обычное видео с помощью VideoView, но не было настройки, позволяющей охватить весь экран, поэтому я попытался добавить его с использованием вида поверхности, но есть некоторая проблема.Приложение останавливается сразу после запуска.

Ниже приведен мой код: -

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/home_container"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <SurfaceView
        android:id="@+id/surface"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:paddingTop="10dip" />
</FrameLayout>

MainActivity.java

public class MainActivity extends Activity implements SurfaceHolder.Callback {

    private MediaPlayer mp = null;

    SurfaceView mSurfaceView=null;



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




        mp = new MediaPlayer();
        mSurfaceView = (SurfaceView) findViewById(R.id.surface);
        mSurfaceView.getHolder().addCallback(this);


        mSurfaceView.getHolder().addCallback(this);





    @Override
    public void surfaceCreated(SurfaceHolder holder) {


        Uri video = Uri.parse("android.resource://" + getPackageName() + "/"
                + R.raw.introduction);

        try {
            mp.setDataSource(String.valueOf(video));
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            mp.prepare();
        } catch (IOException e) {
            e.printStackTrace();
        }

        //Get the dimensions of the video
        int videoWidth = mp.getVideoWidth();
        int videoHeight = mp.getVideoHeight();

        //Get the width of the screen
        int screenWidth = getWindowManager().getDefaultDisplay().getWidth();

        //Get the SurfaceView layout parameters
        android.view.ViewGroup.LayoutParams lp = mSurfaceView.getLayoutParams();

        //Set the width of the SurfaceView to the width of the screen
        lp.width = screenWidth;

        //Set the height of the SurfaceView to match the aspect ratio of the video
        //be sure to cast these as floats otherwise the calculation will likely be 0
        lp.height = (int) (((float)videoHeight / (float)videoWidth) * (float)screenWidth);

        //Commit the layout parameters
        mSurfaceView.setLayoutParams(lp);

        //Start video
        mp.setDisplay(holder);
        mp.start();

        mp.setDisplay(holder);



    }

    @Override
    public void surfaceChanged(SurfaceHolder surfaceHolder, int i, int i1, int i2) {

    }

    @Override
    public void surfaceDestroyed(SurfaceHolder surfaceHolder) {

    }
}

Ниже приведены одинаковые журналы: -

2019-06-12 18: 38: 16.128 4261-4261/?I / art: Не поздно - включение -Xcheck: jni (уже включено) 2019-06-12 18: 38: 16.129 4261-4261 /?W / art: Неожиданный вариант ЦП для X86 с использованием значений по умолчанию: x86 2019-06-12 18: 38: 16.504 4261-4261 / com.example.liveinbliss W / System: ClassLoader ссылается на неизвестный путь: /data/app/com.example.liveinbliss-1 / lib / x86 2019-06-12 18: 38: 16.517 4261-4261 / com.example.liveinbliss I / InstantRun: запуск сервера мгновенного запуска: это основной процесс 2019-06-12 18: 38: 16.647 4261-4261 / com.example.liveinbliss D / AndroidRuntime: завершение работы VM

--------- beginning of crash 2019-06-12 18:38:16.647 4261-4261/com.example.liveinbliss E/AndroidRuntime: FATAL EXCEPTION:

main Процесс: com.example.liveinbliss, PID: 4261 java.lang.RuntimeException: невозможно запустить действие ComponentInfo {com.example.liveinbliss / com.example.liveinbliss.MainActivity}: java.lang.NullPointerException: попытка вызвать виртуальный метод «void android.widget.Button.setOnClickListener (android.view.View $ OnClickListener)» для ссылки на пустой объект на андроиде.app.ActivityThread.performLaunchActivity (ActivityThread.java:2665) в android.app.ActivityThread.handleLaunchActivity (ActivityThread.java:2726) в android.app.ActivityThread.-wrap12 (ActivityThread.java) в android.app.ActivityThread $ H.handleMessage (ActivityThread.java:1477) в android.os.Handler.dispatchMessage (Handler.java:102) в android.os.Looper.loop (Looper.java:154) вandroid.app.ActivityThread.main (ActivityThread.java:6119) в java.lang.reflect.Method.invoke (собственный метод) в com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run (ZygoteInit.java:886) вcom.android.internal.os.ZygoteInit.main (ZygoteInit.java:776) Вызывается: java.lang.NullPointerException: попытка вызвать виртуальный метод void android.widget.Button.setOnClickListener (android.view.View $ OnClickListener)'на пустую ссылку на объект в com.example.liveinbliss.MainActivity.onCreate (MainActivity.java:48) в android.app.Activity.performCreate (Activity.java:6679) в android.app.Instrumentation.callActivityOnCreate (Instrumentation.java): 1118) в android.app.ActivityThread.performLaunchActivity (ActivityThread.java:2618) в android.app.ActivityThread.handleLaunchActivity (ActivityThread.java:2726)

    at android.app.ActivityThread.-wrap12(ActivityThread.java) 
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477) 
    at android.os.Handler.dispatchMessage(Handler.java:102) 
    at android.os.Looper.loop(Looper.java:154) 
    at android.app.ActivityThread.main(ActivityThread.java:6119) 
    at java.lang.reflect.Method.invoke(Native Method) 
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)

    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)

1 Ответ

0 голосов
/ 12 июня 2019

Попробуйте это:

public class MainActivity extends Activity implements SurfaceHolder.Callback {

    private MediaPlayer mp = null;

    SurfaceView mSurfaceView=null;

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

        mp = MediaPlayer.create(this, R.raw.perf); 
        mSurfaceView = (SurfaceView) findViewById(R.raw.introduction);
        mSurfaceView.getHolder().addCallback(this);


        mSurfaceView.getHolder().addCallback(this);

    @Override
    public void surfaceCreated(SurfaceHolder holder) {


        Uri video = Uri.parse("android.resource://" + getPackageName() + "/"
                + R.raw.introduction);

        try {
            mp.setDataSource(String.valueOf(video));
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            mp.prepare();
        } catch (IOException e) {
            e.printStackTrace();
        }

        //Get the dimensions of the video
        int videoWidth = mp.getVideoWidth();
        int videoHeight = mp.getVideoHeight();

        //Get the width of the screen
        int screenWidth = getWindowManager().getDefaultDisplay().getWidth();

        //Get the SurfaceView layout parameters
        android.view.ViewGroup.LayoutParams lp = mSurfaceView.getLayoutParams();

        //Set the width of the SurfaceView to the width of the screen
        lp.width = screenWidth;

        //Set the height of the SurfaceView to match the aspect ratio of the video
        //be sure to cast these as floats otherwise the calculation will likely be 0
        lp.height = (int) (((float)videoHeight / (float)videoWidth) * (float)screenWidth);

        //Commit the layout parameters
        mSurfaceView.setLayoutParams(lp);

        //Start video
        mp.setDisplay(holder);
        mp.start();

        mp.setDisplay(holder);



    }

    @Override
    public void surfaceChanged(SurfaceHolder surfaceHolder, int i, int i1, int i2) {

    }

    @Override
    public void surfaceDestroyed(SurfaceHolder surfaceHolder) {

    }
}
...