簡體   English   中英

如何防止手機屏幕關閉后音樂停止播放?

[英]How to prevent music to stop after the phone's screen goes off?

我正在制作一個播放背景音樂的應用程序。 當我的手機屏幕關閉(或進入睡眠狀態)時,音樂就會停止,並且我希望它也能在屏幕關閉后播放。

這是我的代碼。

MediaPlayer ring= MediaPlayer.create(MainActivity.this,R.raw.backgroundmusic);
ring.start();
ring.setLooping(true);

MediaPlayer類可用於控制音頻/視頻文件和流的播放。 在VideoView中可以找到有關如何使用此類中的方法的示例。 媒體播放器

public class SoundService extends Service {
    private static final String TAG = null;
    MediaPlayer player;
    public IBinder onBind(Intent arg0) {

        return null;
    }
    @Override
    public void onCreate() {
        super.onCreate();
        player = MediaPlayer.create(this, R.raw.idil);
        player.setLooping(true); // Set looping
        player.setVolume(100,100);

    }
    public int onStartCommand(Intent intent, int flags, int startId) {
        player.start();
        return 1;
    }

    public void onStart(Intent intent, int startId) {
        // TO DO
    }
    public IBinder onUnBind(Intent arg0) {
        // TO DO Auto-generated method
        return null;
    }

    public void onStop() {

    }
    public void onPause() {

    }
    @Override
    public void onDestroy() {
        player.stop();
        player.release();
    }

    @Override
    public void onLowMemory() {

    }
}

  Intent svc=new Intent(this, SoundService.class);
  startService(svc);

確保您已將服務添加到清單中。

<service android:enabled="true" android:name=".SoundService" />

您應該考慮使用Service

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM