如何处理在线媒体播放器的网络状态变化(WiFi或移动数据之间的网络转移)?

时间:2018-10-26 10:01:14

标签: java android broadcastreceiver android-mediaplayer

在我的应用中,有一个媒体播放器正在播放流URL。 当互联网连接可用时,播放器以oncreate方法启动。我有一个广播接收器,它检查与互联网的连接并通知用户。我在这里面临的一个问题是,当我的应用程序从Wifi切换到蜂窝网络时,媒体播放器应稍作暂停,然后重新启动,因为网络可以再次使用。但是我无法找到我该如何实现的逻辑? 这是我的示例代码,请解决问题? 任何帮助将不胜感激。

清单:

<uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />

    <receiver android:name=".receivers.NetworkChangeReciever">
        <intent-filter>
            <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
        </intent-filter>
    </receiver>

主要活动:

private BroadcastReceiver mNetworkReceiver;
    static TextView tv_check_connection;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tv_check_connection=(TextView) findViewById(R.id.tv_check_connection);
        mNetworkReceiver = new NetworkChangeReciever();
        registerNetworkBroadcastForNougat();

       // checkNetworkStatus();

        mSelectedTrackTitle = (TextView) findViewById(R.id.selected_track_title);
        nowplaying = (TextView) findViewById(R.id.nowplaying);
        mPlayerControl = (ImageView) findViewById(R.id.player_control);
        mPlayerControl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                togglePlayPause();
            }
        });

        mSelectedTrackTitle.setText("FM World Pakistan");
        nowplaying.setText("Now Playing");
        mPlayerControl.setImageResource(R.drawable.ic_pause_circle_filled);

            mMediaPlayer = new MediaPlayer();
            mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            try {
                mMediaPlayer.setDataSource(url);
                mMediaPlayer.prepare();
                mMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                    @Override
                    public void onPrepared(MediaPlayer mp) {
                        mMediaPlayer.start();
                    }
                });

            } catch (IOException e) {
                e.printStackTrace();
                nowplaying.setText("Offline");
                Toast.makeText(MainActivity.this, "Radio Offline", Toast.LENGTH_LONG).show();
                mPlayerControl.setImageResource(R.drawable.ic_play_circle_filled);
            }
public static void dialog(boolean value){

        if(value){
            tv_check_connection.setText("We are back !!!");
            tv_check_connection.setBackgroundResource(R.color.neton);
            tv_check_connection.setTextColor(Color.WHITE);

            Handler handler = new Handler();
            Runnable delayrunnable = new Runnable() {
                @Override
                public void run() {
                    tv_check_connection.setVisibility(View.GONE);
                }
            };
            handler.postDelayed(delayrunnable, 3000);
        }else {
            tv_check_connection.setVisibility(View.VISIBLE);
            tv_check_connection.setText("Could not connect to Internet.");
            tv_check_connection.setBackgroundResource(R.color.colorAccent);
            tv_check_connection.setTextColor(Color.WHITE);
            nowplaying.setText("Buffering...");
            mPlayerControl.setImageResource(R.drawable.ic_play_circle_filled);
        }
    }


    private void registerNetworkBroadcastForNougat() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            registerReceiver(mNetworkReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            registerReceiver(mNetworkReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
        }
    }

    protected void unregisterNetworkChanges() {
        try {
            unregisterReceiver(mNetworkReceiver);
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        }
    }
private void togglePlayPause() {
        if (mMediaPlayer.isPlaying()) {
           mMediaPlayer.pause();
            nowplaying.setText("Offline");
            mPlayerControl.setImageResource(R.drawable.ic_play_circle_filled);
        } else {
            mMediaPlayer.start();
            nowplaying.setText("Now Playing");
            mPlayerControl.setImageResource(R.drawable.ic_pause_circle_filled);
       }
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterNetworkChanges();
        if (mMediaPlayer != null) {
            if (mMediaPlayer.isPlaying()) {
                mMediaPlayer.stop();
            }
            mMediaPlayer.release();
            mMediaPlayer = null;
        }
    }

接收器类别:

public class NetworkChangeReciever extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        try
        {
            if (isOnline(context)) {
                dialog(true);
                Log.e("Hi", "Online Connect Intenet ");
            } else {
                dialog(false);
                Log.e("Sorry","Conectivity Failure !!! ");
            }
        } catch (NullPointerException e) {
            e.printStackTrace();
        }

    }
    private boolean isOnline(Context context) {
        try {
            ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo netInfo = cm.getActiveNetworkInfo();
            //should check null because in airplane mode it will be null
            return (netInfo != null && netInfo.isConnected());
        } catch (NullPointerException e) {
            e.printStackTrace();
            return false;
        }
    }

1 个答案:

答案 0 :(得分:1)

我发现了一个解决方案,例如,将媒体播放器声明为静态;我们可以在dialog()

中对其进行初始化

公共静态无效对话框(布尔值){

     if(value){
            tv_check_connection.setText("We are back !!!");
            tv_check_connection.setBackgroundResource(R.color.neton);
            tv_check_connection.setTextColor(Color.WHITE);
//recreate media player

            Handler handler = new Handler();
            Runnable delayrunnable = new Runnable() {
                @Override
                public void run() {
                    tv_check_connection.setVisibility(View.GONE);
                }
            };
            handler.postDelayed(delayrunnable, 3000);
        }else {
            tv_check_connection.setVisibility(View.VISIBLE);
            tv_check_connection.setText("Could not connect to Internet.");
            tv_check_connection.setBackgroundResource(R.color.colorAccent);
            tv_check_connection.setTextColor(Color.WHITE);
            nowplaying.setText("Buffering...");
            mPlayerControl.setImageResource(R.drawable.ic_play_circle_filled);
//pause media player
        }
    }