2012-10-10 79 views
10

我有一個Android應用程序,它使用MediaPlayer類從Internet播放流式音頻。如何在Android的後臺播放流式音頻?

當 用戶點擊主頁按鈕運行其他應用程序時,如何讓它繼續在後臺播放音頻?

在運行其他應用程序時,我希望它繼續播放音頻。

回答

10

你必須使用一些名爲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

+0

謝謝,我來看看服務! – Winston

4

您需要實施服務才能在後臺播放媒體,而不會將其綁定到開始播放的活動。看看this example

+0

感謝您對服務和鏈接的提示! – Winston

1

的關鍵是確定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); 

Complete code of this example.