简体   繁体   中英

Android: Media Player stream stops playing after some mintunes

I am trying to stream shoutcast URL in my app through media player and it works fine ( no stops after sometime) for API 14 and older (ie. in my friend mobile it works fine who has note 2) but it stops playing after sometime for higher API (ie: my android version is 7 Samsung galaxy S6 edge plus) and it stops for me after sometime.

How can i solve this issue?

below is the code:

ActivityRadio.java

public class ActivityRadio extends BaseActivity {

    private String[] navMenuTitles;
    private TypedArray navMenuIcons;

    Button startButton, stopButton;
    static Context context;
    boolean isPlaying;
    Intent streamService;
    SharedPreferences prefs;

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

         context = getApplicationContext();

        navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items); // load
        // titles
        // from
        // strings.xml

navMenuIcons = getResources()
.obtainTypedArray(R.array.nav_drawer_icons);// load icons from
// strings.xml

set(navMenuTitles, navMenuIcons);
AdView adView = (AdView)this.findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder()
//.addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
// .addTestDevice("TEST_DEVICE_ID")
.build();
adView.loadAd(adRequest);

        startButton = (Button) findViewById(R.id.startButton);
        stopButton = (Button) findViewById(R.id.stopButton);
        prefs = PreferenceManager.getDefaultSharedPreferences(context);
        getPrefs();
        streamService = new Intent(ActivityRadio.this, ServiceRadio.class);    

        startButton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                startService(streamService);
                startButton.setEnabled(false);
            }
        });

        stopButton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                stopService(streamService);
                startButton.setEnabled(true);
            }
        });
    }

    public void getPrefs() {
            isPlaying = prefs.getBoolean("isPlaying", false);
            if (isPlaying) startButton.setEnabled(false);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK ) {
            Intent intent = new Intent(ActivityRadio.this, ActivityMain.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            intent.putExtra("EXIT", true);
            startActivity(intent);
        }
        return super.onKeyDown(keyCode, event);
    }

}

ServiceRadio.java

public class ServiceRadio extends Service implements OnAudioFocusChangeListener {
    private static final String TAG = "StreamService";
    MediaPlayer mp;
    boolean isPlaying;
    SharedPreferences prefs;
    SharedPreferences.Editor editor;
    private AudioManager mAudioManager;
    Notification n;
    NotificationManager notificationManager;
    // Change this int to some number specifically for this app
    int notifId = 5315;



    @Override
    public IBinder onBind(Intent arg0) {
        // TODO Auto-generated method stub
        return null;
    }

    @SuppressWarnings("deprecation")
    @Override
    public void onCreate() {
        super.onCreate();
        Log.d(TAG, "onCreate");

        // Init the SharedPreferences and Editor
        prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
        editor = prefs.edit();

        // Set up the buffering notification
        notificationManager = (NotificationManager) getApplicationContext()
                .getSystemService(NOTIFICATION_SERVICE);
        Context context = getApplicationContext();

        String notifTitle = context.getResources().getString(R.string.app_name);
        String notifMessage = context.getResources().getString(R.string.buffering);

        n = new Notification();
        n.icon = R.drawable.icon;
        n.tickerText = "Buffering";
        n.when = System.currentTimeMillis();

        Intent nIntent = new Intent(context, ActivityRadio.class);
        PendingIntent pIntent = PendingIntent.getActivity(context, 0, nIntent, 0);

        n.setLatestEventInfo(context, notifTitle, notifMessage, pIntent);

        notificationManager.notify(notifId, n);



        // It's very important that you put the IP/URL of your ShoutCast stream here
        // Otherwise you'll get Webcom Radio
        String url = "http://listen.shoutcast.com/fmd";
        mp = new MediaPlayer();
        mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
        try {
            mp.setDataSource(url);
            mp.prepare();
        } catch (IllegalArgumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SecurityException e) {
            // TODO Auto-generated catch block
            Log.e(TAG, "SecurityException");
        } catch (IllegalStateException e) {
            // TODO Auto-generated catch block
            Log.e(TAG, "IllegalStateException");
        } catch (IOException e) {
            // TODO Auto-generated catch block
            Log.e(TAG, "IOException");
        }

         mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
            mAudioManager.requestAudioFocus(this, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);

    }

    @Override
    public void onAudioFocusChange(int focusChange) {
        if(focusChange<=0) {
            mp.pause();
        } else {
            mp.start();
        }
    }

    @SuppressWarnings("deprecation")
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d(TAG, "onStart");
        mp.start();



        // Set the isPlaying preference to true
        editor.putBoolean("isPlaying", true);
        editor.commit();

        Context context = getApplicationContext();
        String notifTitle = context.getResources().getString(R.string.app_name);
        String notifMessage = context.getResources().getString(R.string.now_playing);

        n.icon = R.drawable.icon;
        n.tickerText = notifMessage;
        n.flags = Notification.FLAG_NO_CLEAR;
        n.when = System.currentTimeMillis();

        Intent nIntent = new Intent(context, ActivityRadio.class);
        PendingIntent pIntent = PendingIntent.getActivity(context, 0, nIntent, 0);

        n.setLatestEventInfo(context, notifTitle, notifMessage, pIntent);
        // Change 5315 to some nother number
        notificationManager.notify(notifId, n);

        return Service.START_STICKY; // not supported in SDK
    }

    @Override
    public void onDestroy() {
        Log.d(TAG, "onDestroy");
        mp.stop();
        mp.release();
        mp = null;
        editor.putBoolean("isPlaying", false);
        editor.commit();
        notificationManager.cancel(notifId);
        mAudioManager.abandonAudioFocus(this);
    }

}

use the following line startForeground(notifId, n) instead of this one notificationManager.notify(notifId, n); When using notifications in a service, the notification also must be persistent.

instead of use startService(streamService); please use

    try {
        Intent playbackServiceIntent = new Intent(this, MusicService.class);
        startService(playbackServiceIntent);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            startForegroundService(playbackServiceIntent);
        }
    }catch (Exception e){
        e.printStackTrace();
    }

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