如何在安卓设备上在后台播放流媒体音频



我有一个Android应用程序,它使用MediaPlayer类播放来自互联网的流音频。

如何让它继续在后台播放音频,当 用户点击主页按钮运行其他应用程序?

在运行其他应用程序时,我希望它继续播放音频。

你必须使用一种叫做Android服务的东西。

从文档中:

"服务是一个应用程序组件,表示应用程序在不与用户交互的情况下执行长时间运行的操作的愿望,或者为其他应用程序提供功能以供使用。

以下是使用服务入门的出色官方指南:http://developer.android.com/guide/components/services.html

这里有一个关于构建音频播放器的好教程:http://www.androidhive.info/2012/03/android-building-audio-player-tutorial/

以下是构建流音乐播放器的视频教程:http://www.youtube.com/watch?v=LKL-efbiIAM

您需要实现一个服务才能在后台播放媒体,而不会将其绑定到开始播放的活动。看看这个例子。

关键是定义Service.START_STICKY继续在后台播放:

   public int onStartCommand(Intent intent, int flags, int startId) {
        myMediaPlayer.start();
        return Service.START_STICKY;
    }

Service.START_STICKY:如果此服务的进程在 已启动系统将尝试重新创建服务。

这是执行此操作的示例:

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;
/**
 * Created by jorgesys.
 */
/* Add declaration of this service into the AndroidManifest.xml inside application tag*/
public class BackgroundSoundService extends Service {
    private static final String TAG = "BackgroundSoundService";
    MediaPlayer player;
    public IBinder onBind(Intent arg0) {
        Log.i(TAG, "onBind()" );
        return null;
    }
    @Override
    public void onCreate() {
        super.onCreate();
        player = MediaPlayer.create(this, R.raw.jorgesys_song);
        player.setLooping(true); // Set looping
        player.setVolume(100,100);
        Toast.makeText(this, "Service started...", Toast.LENGTH_SHORT).show();
        Log.i(TAG, "onCreate() , service started...");
    }
    public int onStartCommand(Intent intent, int flags, int startId) {
        player.start();
        return Service.START_STICKY;
    }
    public IBinder onUnBind(Intent arg0) {
        Log.i(TAG, "onUnBind()");
        return null;
    }
    public void onStop() {
        Log.i(TAG, "onStop()");
    }
    public void onPause() {
        Log.i(TAG, "onPause()");
    }
    @Override
    public void onDestroy() {
        player.stop();
        player.release();
        Toast.makeText(this, "Service stopped...", Toast.LENGTH_SHORT).show();
        Log.i(TAG, "onCreate() , service stopped...");
    }
    @Override
    public void onLowMemory() {
        Log.i(TAG, "onLowMemory()");
    }
}

启动服务:

Intent myService = new Intent(MainActivity.this, BackgroundSoundService.class);
startService(myService);

停止服务:

Intent myService = new Intent(MainActivity.this, BackgroundSoundService.class);
stopService(myService);

此示例的完整代码。

最新更新