简体   繁体   中英

How to handle online media player on network state change (network shifts between WiFi or mobile data)?

In my app there is a media player which is playing streamed url. The player starts in oncreate method when the connection to internet is available.I have a broadcast receiver which checks the connection to the internet and notify the user. I am facing a problem here that when my app shifts from Wifi to cellular network, media player should take a little pause and starts again because the network is available again. But i'am unable to find the logic that how can i achieve this? Here is my sample code,Kindly solve the issue? Any help will be grateful.

Manifest:

<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>

Main Activity:

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;
        }
    }

Receiver Class:

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;
        }
    }

I found a solution as, if media player is declared as static; we can reinitialize it in dialog()

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);
//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
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM