要从URL查看视频流,可以使用Android的MediaPlayer类来实现。下面是一个包含代码示例的解决方法:
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import androidx.appcompat.app.AppCompatActivity;
import java.io.IOException;
public class MainActivity extends AppCompatActivity implements SurfaceHolder.Callback {
private MediaPlayer mediaPlayer;
private SurfaceView surfaceView;
private SurfaceHolder surfaceHolder;
private String videoUrl = "http://example.com/video.mp4";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
surfaceView = findViewById(R.id.surfaceView);
surfaceHolder = surfaceView.getHolder();
surfaceHolder.addCallback(this);
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
try {
mediaPlayer = new MediaPlayer();
mediaPlayer.setDisplay(holder);
mediaPlayer.setDataSource(getApplicationContext(), Uri.parse(videoUrl));
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
@Override
public void onPrepared(MediaPlayer mp) {
mediaPlayer.start();
}
});
mediaPlayer.prepareAsync();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
mediaPlayer.release();
}
}
在上面的代码中,我们通过实现SurfaceHolder.Callback接口来监听SurfaceView的创建、改变和销毁事件。在surfaceCreated()方法中,我们创建了一个MediaPlayer实例,并将其与SurfaceHolder绑定。然后,我们设置了视频源的URL,并在MediaPlayer准备好后开始播放。
请注意,上述代码中的videoUrl应该替换为实际的视频URL。另外,你可能还需要在后台线程中执行网络请求,以避免在主线程中执行耗时操作。
这样,当你运行应用程序时,你将能够从URL查看视频流。