java - Android:媒体播放器流在几分钟后停止播放

标签 java android

我正在尝试通过媒体播放器在我的应用程序中流式传输Shoutcast URL,对于API 14及更早版本(即在我 friend 的手机中,它在有注释2的情况下工作正常),它工作正常(一段时间后不会停止),但对于更高的API,它会在一段时间后停止播放(即:我的Android版本是7 Samsung Galaxy S6 Edge Plus),一段时间后它会停止播放。

如何解决这个问题?

下面是代码:

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

}

最佳答案

使用下面一行 startForeground(notifId, n) 而不是这一行 notificationManager.notify(notifId, n); 在服务中使用通知时,通知也必须是持久的。

关于java - Android:媒体播放器流在几分钟后停止播放,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48162629/

相关文章:

java - 特定范围的颜色映射

java - 如何将 ImageIcon 添加到 JToolBar

java - 迭代解决方案的递归

android - 如何通过单击图像按钮动态设置编辑文本可编辑?

android - proguard-rules.pro 中的规则顺序重要吗?

android - 用于消息(IM)和文件发送的Skype android api

java - 在 Java GWT 中使用 LDAP,在本地主机上工作但不在服务器上 -> 错误代码 34

java - Netty客户端向服务器发送保持 Activity 状态

java - 使用 Retrofit2 和多个内联项的简单 XML 序列化

javascript - 过渡 react 导航标题背景颜色