播放视频前如何检查互联网连接?

时间:2019-09-26 07:51:05

标签: android kotlin exoplayer

当我从exoplayer单击播放按钮时,我已经创建了MainActivity的活动,它应该打开我的exoplayer活动文件并播放我的hls源。即使没有移动数据或wifi连接,它也会尝试打开exoplayer并显示带有控件的黑色。如何在某些情况下解决此问题。我的android项目在kotlin中。我正在使用exoplayer 2.6.0版。

    package com.example.sample

    import android.net.Uri
    import android.os.Bundle
    import android.os.Handler
    import android.view.View
    import android.view.WindowManager
    import androidx.appcompat.app.AppCompatActivity
    import com.google.android.exoplayer2.DefaultLoadControl
    import com.google.android.exoplayer2.DefaultRenderersFactory
    import com.google.android.exoplayer2.ExoPlayerFactory
    import com.google.android.exoplayer2.SimpleExoPlayer
    import com.google.android.exoplayer2.source.hls.HlsMediaSource
    import com.google.android.exoplayer2.trackselection.DefaultTrackSelector
    import com.google.android.exoplayer2.ui.SimpleExoPlayerView
    import com.google.android.exoplayer2.upstream.DefaultDataSourceFactory

    class playlive : AppCompatActivity() {

        private var player: SimpleExoPlayer? = null
        private val handler = Handler()

        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            setContentView(R.layout.activity_playlive)

            window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_FULLSCREEN
            actionBar?.hide()
            window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)

         play()

        }

        private fun play(){
        player = 
        ExoPlayerFactory.newSimpleInstance(DefaultRenderersFactory(this), 
        DefaultTrackSelector(), DefaultLoadControl())
        val playerView = findViewById<SimpleExoPlayerView>(R.id.player_view)
        val uri = Uri.parse("http://localhost/tv2hls/live.m3u8")

        playerView.player = player

        val dataSourceFactory = DefaultDataSourceFactory(this, "user-agent")
        val mediaSource = HlsMediaSource(uri, dataSourceFactory, handler, null)

        player?.prepare(mediaSource)
        player?.playWhenReady = true
    }

        override fun onStop() {
            super.onStop()
            releasePlayer()
            releaseInstance()
        }

        override fun onResume() {
            super.onResume()
            releasePlayer()
            resumePlayer()
        }


        override fun onDestroy() {
            super.onDestroy()
            releasePlayer()
            releaseInstance()
        }

        private fun releasePlayer(){
            player?.release()
        }

        private fun resumePlayer(){
            play()
        }

    }

2 个答案:

答案 0 :(得分:0)

使用此功能检查网络可用性

fun isNetwork(): Boolean{
        val connectivityManager = context?.getSystemService(CONNECTIVITY_SERVICE) as ConnectivityManager
        val networkInfo = connectivityManager.activeNetworkInfo
        // In here we return true if network is not null and Network is connected
        return if(networkInfo != null && networkInfo.isConnected){
            true
        }

    }

然后调用此函数

if(isNetwork()){

  //Do your work here
}
else{

  //Network is not available do another work
}

答案 1 :(得分:0)

您可以使用Android Jetpack组件中的MutableLiveData,如下所示。即使您已连接到WiFi,但WiFi没有Internet连接,这也将为您提供帮助。

object Network {

private var mMutableData : MutableLiveData<Boolean>? =null
fun isNetworkAvailableWithInternetAccess(mContext: Context): LiveData<Boolean> {
    mMutableData = MutableLiveData()
    val cm = mContext.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
    val networkInfo: NetworkInfo?
    networkInfo = cm.activeNetworkInfo
    if (networkInfo != null && networkInfo.isConnected) isInternetAvailable()
    return mMutableData!!
}

private var parentJob = Job()
private val coRoutineContext: CoroutineContext
    get() = parentJob + Dispatchers.Main

private fun isInternetAvailable() {
    val scope = CoroutineScope(coRoutineContext)
    scope.launch(Dispatchers.IO) {
        try {
            val sock = Socket()
            val socketAddress = InetSocketAddress("8.8.8.8", 53)

            sock.connect(socketAddress, 2000) // This will block no more than timeoutMs
            sock.close()

            mMutableData!!.postValue(true)

        } catch (e: IOException) {
            mMutableData!!.postValue(false)
        }
    }
}
}

使用:

Network.isNetworkAvailableWithInternetAccess(context).observe(this, Observer {
        if (it != null) {
            if (it) {
             //Do your work here
            }else{
            //Network is not available do another work
            }
    })