我有一个Android应用程序,它使用MediaPlayer
类从Internet播放流式音频。如何在Android的后台播放流式音频?
当 用户点击主页按钮运行其他应用程序时,如何让它继续在后台播放音频?
在运行其他应用程序时,我希望它继续播放音频。
我有一个Android应用程序,它使用MediaPlayer
类从Internet播放流式音频。如何在Android的后台播放流式音频?
当 用户点击主页按钮运行其他应用程序时,如何让它继续在后台播放音频?
在运行其他应用程序时,我希望它继续播放音频。
你必须使用一些名为Android服务。
从文档:
“A Service是表示任一应用程序的欲望以执行更长的运行的操作,同时不与用户交互或用于其它应用程序使用,以提供功能的应用程序组件”。
这里是极好的官方指导使用服务,让您开始: 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);
谢谢,我来看看服务! – Winston