Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/219.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 音乐播放器的实现_Java_Android_Mp3_Audio Player - Fatal编程技术网

Java 音乐播放器的实现

Java 音乐播放器的实现,java,android,mp3,audio-player,Java,Android,Mp3,Audio Player,我是Android新手。我正在尝试创建一个音乐播放器,它将根据计数(由Rc变量控制)和按钮顺序(由BitCount变量控制)来播放特定的MP3。我有一个停止按钮,点击它我应该可以停止音乐 我的问题是,当UI位于前台时,一切正常,但当屏幕转到后台时,音乐也开始运行(让音乐在后台运行没关系),但当我再次将UI从后台转到前台时,而不是单击“停止”按钮,我无法停止音乐,它会持续运行。当我旋转手机时,同样的问题也会发生 代码: 当您关闭应用程序时,您的活动将被销毁,因此对您的媒体播放器变量的引用将丢失。当

我是Android新手。我正在尝试创建一个音乐播放器,它将根据计数(由
Rc
变量控制)和按钮顺序(由
BitCount
变量控制)来播放特定的MP3。我有一个停止按钮,点击它我应该可以停止音乐

我的问题是,当UI位于前台时,一切正常,但当屏幕转到后台时,音乐也开始运行(让音乐在后台运行没关系),但当我再次将UI从后台转到前台时,而不是单击“停止”按钮,我无法停止音乐,它会持续运行。当我旋转手机时,同样的问题也会发生

代码:


当您关闭应用程序时,您的活动将被销毁,因此对您的媒体播放器变量的引用将丢失。当你重新创建你的活动时,你会得到一组新的引用,因此你无法停止它

您必须创建一个名为MediaPlayerService的服务,该服务将处理所有与媒体相关的操作,如播放、暂停等

您可以在此处阅读有关服务的信息:

如果您想要一个媒体播放器的示例,可以查看RandomMusicLayer,这是android在android示例项目中提供的一个优秀的媒体播放器示例

这是我对MediaPlayerService的实现

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.cyberinsane.musicplayerlibrary"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
    android:minSdkVersion="8"
    android:targetSdkVersion="18" />

<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name="com.cyberinsane.musicplayerlibrary.MediaPlayerActivity"
        android:label="@string/app_name"
        android:launchMode="singleTask" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <service
        android:name="com.cyberinsane.musicplayerlibrary.MediaPlayerService"
        android:exported="false" >
        <intent-filter>
            <action android:name="com.cyberinsane.musicplayerlibrary.action.TOGGLE_PLAYBACK" />
            <action android:name="com.cyberinsane.musicplayerlibrary.action.PLAY" />
            <action android:name="com.cyberinsane.musicplayerlibrary.action.PAUSE" />
            <action android:name="com.cyberinsane.musicplayerlibrary.action.SKIP" />
            <action android:name="com.cyberinsane.musicplayerlibrary.action.REWIND" />
            <action android:name="com.cyberinsane.musicplayerlibrary.action.STOP" />
        </intent-filter>
    </service>
</application>

</manifest>
MediaPlayerService类:

package com.cyberinsane.musicplayerlibrary;

import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnErrorListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.net.Uri;
import android.os.Binder;
import android.os.IBinder;
import android.os.PowerManager;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import android.widget.Toast;

public class MediaPlayerService extends Service implements OnCompletionListener, OnPreparedListener, OnErrorListener {

private static final int NOTIFICATION_ID = 1;
public static final String INTENT_URL = "url";

public enum MediaState {
    Playing, Paused, Stopped
}

private MediaState mState = MediaState.Stopped;
private MediaPlayer mPlayer;

private NotificationManager mNotificationManager;

public String mCurrentUrl = "";

public static final String ACTION_TOGGLE_PLAYBACK = "com.cyberinsane.musicplayerlibrary.action.TOGGLE_PLAYBACK";
public static final String ACTION_PLAY = "com.cyberinsane.musicplayerlibrary.action.PLAY";
public static final String ACTION_PAUSE = "com.cyberinsane.musicplayerlibrary.action.PAUSE";
public static final String ACTION_STOP = "com.cyberinsane.musicplayerlibrary.action.STOP";

@Override
public void onCreate() {
    super.onCreate();
    mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    if (intent != null) {
        String action = intent.getAction();
        String url = intent.getExtras().getString(INTENT_URL);
        if (url != null) {
            if (!url.equals(mCurrentUrl)) {
                mCurrentUrl = url;
                mState = MediaState.Stopped;
                relaxResources(true);
                processPlayRequest();
            } else {
                if (action.equals(ACTION_TOGGLE_PLAYBACK)) {
                    processTogglePlaybackRequest();
                } else if (action.equals(ACTION_PLAY)) {
                    processPlayRequest();
                } else if (action.equals(ACTION_PAUSE)) {
                    processPauseRequest();
                } else if (action.equals(ACTION_STOP)) {
                    processStopRequest(false);
                }
            }
        }
    }

    return START_STICKY;
}

private void processTogglePlaybackRequest() {
    if (mState == MediaState.Paused || mState == MediaState.Stopped) {
        processPlayRequest();
    } else {
        processPauseRequest();
    }
}

private void processPlayRequest() {
    try {
        if (mState == MediaState.Stopped) {
            createMediaPlayerIfNeeded();
            mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            mPlayer.setDataSource(getApplicationContext(), Uri.parse(mCurrentUrl));
            mPlayer.prepare();

        } else if (mState == MediaState.Paused) {
            mState = MediaState.Playing;
            setUpAsForeground("Playing...");
            if (!mPlayer.isPlaying()) {
                mPlayer.start();

                if (mIMediaPlayer != null) {
                    mIMediaPlayer.onAudioPlay();
                }
            }
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

private void processPauseRequest() {
    if (mState == MediaState.Playing) {
        mState = MediaState.Paused;
        mPlayer.pause();
        relaxResources(false);

        if (mIMediaPlayer != null) {
            mIMediaPlayer.onAudioPause();
        }
    }
}

private void processStopRequest(boolean force) {
    if (mState == MediaState.Playing || mState == MediaState.Paused || force) {
        mState = MediaState.Stopped;
        relaxResources(true);
        stopSelf();
    }
}

private void createMediaPlayerIfNeeded() {
    if (mPlayer == null) {
        mPlayer = new MediaPlayer();
        mPlayer.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);
        mPlayer.setOnPreparedListener(this);
        mPlayer.setOnCompletionListener(this);
        mPlayer.setOnErrorListener(this);
    } else
        mPlayer.reset();
}

private void relaxResources(boolean releaseMediaPlayer) {
    stopForeground(true);

    if (releaseMediaPlayer && mPlayer != null) {
        mPlayer.reset();
        mPlayer.release();
        mPlayer = null;
    }
}

@Override
public boolean onError(MediaPlayer mp, int what, int extra) {
    Toast.makeText(getApplicationContext(), "Media player error! Resetting.", Toast.LENGTH_SHORT).show();
    Log.e("MusicPlayer", "Error: what=" + String.valueOf(what) + ", extra=" + String.valueOf(extra));

    mState = MediaState.Stopped;
    relaxResources(true);

    if (mIMediaPlayer != null) {
        mIMediaPlayer.onError();
    }
    return true; // true indicates we handled the error
}

@Override
public void onPrepared(MediaPlayer mp) {
    mState = MediaState.Playing;
    updateNotification("Playing...");
    if (!mPlayer.isPlaying()) {
        mPlayer.start();
        if (mIMediaPlayer != null) {
            mIMediaPlayer.onAudioPlay();
        }
    }
}

@Override
public void onCompletion(MediaPlayer mp) {
    mState = MediaState.Stopped;
    relaxResources(true);
    stopSelf();
    if (mIMediaPlayer != null) {
        mIMediaPlayer.onAudioStop();
    }
}

/**
 * Updates the notification.
 */
private void updateNotification(String text) {
    mNotificationManager.notify(NOTIFICATION_ID, buildNotification(text).build());
}

private void setUpAsForeground(String text) {
    startForeground(NOTIFICATION_ID, buildNotification(text).build());
}

private NotificationCompat.Builder buildNotification(String text) {
    NotificationCompat.Builder builder = new NotificationCompat.Builder(this.getApplicationContext());
    builder.setSmallIcon(R.drawable.ic_launcher)
            .setOngoing(true)
            .setContentTitle("Cyberinsane MusicPlayer")
            .setContentText(text)
            .setContentIntent(
                    PendingIntent.getActivity(getApplicationContext(), 0, new Intent(getApplicationContext(),
                            MediaPlayerActivity.class), PendingIntent.FLAG_UPDATE_CURRENT))
            .setContentInfo("Awesome");

    return builder;
}

@Override
public void onDestroy() {
    mState = MediaState.Stopped;
    relaxResources(true);
}

public class LocalBinder extends Binder {
    MediaPlayerService getService() {
        return MediaPlayerService.this;
    }
}

@Override
public IBinder onBind(Intent intent) {
    return mBinder;
}

private final IBinder mBinder = new LocalBinder();
private IMediaPlayer mIMediaPlayer;

public MediaPlayer getMediaPlayer() {
    return mPlayer;
}

public void setIMediaPlayer(IMediaPlayer mediaPlayer) {
    mIMediaPlayer = mediaPlayer;

}

public MediaState getMediaState() {
    return mState;
}

public boolean isPlaying() {
    return (mState == MediaState.Playing);
}

public String getCurrentUrl() {
    return mCurrentUrl;
}

public long duration() {
    if (mPlayer != null) {
        return mPlayer.getDuration();
    }
    return 0;
}

public long position() {
    if (mPlayer != null) {
        return mPlayer.getCurrentPosition();
    }
    return 0;
}

public void seekTo(long position) {
    if (mPlayer != null) {
        mPlayer.seekTo((int) position);
    }
}

}
package com.cyberinsane.musicplayerlibrary;

import java.io.File;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;

public class MediaPlayerActivity extends Activity implements IMediaPlayer {

private ImageButton mButtonPlay;
private EditText mEditTextUrl;
private SeekBar mSeekBarProgress;

private boolean mIsBound;
private String mExtStorePath;

private MediaPlayerService mMediaService;

private Handler mSeekHandler = new Handler();

private Runnable mSeekRunnable = new Runnable() {
    @Override
    public void run() {
        seekStartUpdation();
    }
};

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.media_player_activity);

    mButtonPlay = (ImageButton) findViewById(R.id.buttonPlay);
    mEditTextUrl = (EditText) findViewById(R.id.editTextURL);
    mSeekBarProgress = (SeekBar) findViewById(R.id.seekBarMediaProgress);
    mExtStorePath = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator;

    doBindService();
    initListeners();
}

private void initListeners() {
    mButtonPlay.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            String urlExt = mEditTextUrl.getText().toString();
            if (urlExt != null && !urlExt.equals("")) {
                String url = mExtStorePath + urlExt;
                startService(new Intent(MediaPlayerService.ACTION_TOGGLE_PLAYBACK).putExtra(
                        MediaPlayerService.INTENT_URL, url));
            }
        }
    });

    mSeekBarProgress.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
            mMediaService.seekTo(seekBar.getProgress());
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {
            // empty
        }

        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            // empty
        }
    });
}

@Override
protected void onResume() {
    super.onResume();
    doBindService();
}

@Override
protected void onDestroy() {
    super.onDestroy();
    doUnbindService();
}

@Override
protected void onPause() {
    super.onPause();
    doUnbindService();
}

private ServiceConnection mConnection = new ServiceConnection() {
    @Override
    public void onServiceConnected(ComponentName className, IBinder service) {
        mMediaService = ((MediaPlayerService.LocalBinder) service).getService();
        mMediaService.setIMediaPlayer(MediaPlayerActivity.this);
        setControlState();
    }

    @Override
    public void onServiceDisconnected(ComponentName className) {
        mMediaService = null;
    }
};

private void doBindService() {
    bindService(new Intent(MediaPlayerActivity.this, MediaPlayerService.class), mConnection,
            Context.BIND_AUTO_CREATE);
    mIsBound = true;
}

private void doUnbindService() {
    if (mIsBound) {
        unbindService(mConnection);
        mIsBound = false;
    }
}

@Override
public void onAudioPlay() {
    setPlayerState(true);
}

@Override
public void onAudioPause() {
    setPlayerState(false);
}

@Override
public void onAudioStop() {
    setPlayerState(false);
    mSeekBarProgress.setProgress(0);
}

@Override
public void onError() {
    // handle errors here
}

private void setControlState() {
    if (mMediaService.isPlaying()) {
        mEditTextUrl.setText(mMediaService.getCurrentUrl().replace(mExtStorePath, ""));
        setPlayerState(true);
    } else {
        setPlayerState(false);
    }
}

public void setPlayerState(boolean isPlaying) {
    if (isPlaying) {
        mButtonPlay.setImageResource(R.drawable.ic_pause);
        mSeekBarProgress.setMax((int) mMediaService.duration());
        seekStartUpdation();
    } else {
        mButtonPlay.setImageResource(R.drawable.ic_play);
        seekStopUpdate();
    }
}

public void seekStartUpdation() {
    mSeekBarProgress.setProgress((int) mMediaService.position());
    mSeekHandler.postDelayed(mSeekRunnable, 1000);
}

public void seekStopUpdate() {
    mSeekHandler.removeCallbacks(mSeekRunnable);
}
}
MediaPlayerActivity类:

package com.cyberinsane.musicplayerlibrary;

import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnErrorListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.net.Uri;
import android.os.Binder;
import android.os.IBinder;
import android.os.PowerManager;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import android.widget.Toast;

public class MediaPlayerService extends Service implements OnCompletionListener, OnPreparedListener, OnErrorListener {

private static final int NOTIFICATION_ID = 1;
public static final String INTENT_URL = "url";

public enum MediaState {
    Playing, Paused, Stopped
}

private MediaState mState = MediaState.Stopped;
private MediaPlayer mPlayer;

private NotificationManager mNotificationManager;

public String mCurrentUrl = "";

public static final String ACTION_TOGGLE_PLAYBACK = "com.cyberinsane.musicplayerlibrary.action.TOGGLE_PLAYBACK";
public static final String ACTION_PLAY = "com.cyberinsane.musicplayerlibrary.action.PLAY";
public static final String ACTION_PAUSE = "com.cyberinsane.musicplayerlibrary.action.PAUSE";
public static final String ACTION_STOP = "com.cyberinsane.musicplayerlibrary.action.STOP";

@Override
public void onCreate() {
    super.onCreate();
    mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    if (intent != null) {
        String action = intent.getAction();
        String url = intent.getExtras().getString(INTENT_URL);
        if (url != null) {
            if (!url.equals(mCurrentUrl)) {
                mCurrentUrl = url;
                mState = MediaState.Stopped;
                relaxResources(true);
                processPlayRequest();
            } else {
                if (action.equals(ACTION_TOGGLE_PLAYBACK)) {
                    processTogglePlaybackRequest();
                } else if (action.equals(ACTION_PLAY)) {
                    processPlayRequest();
                } else if (action.equals(ACTION_PAUSE)) {
                    processPauseRequest();
                } else if (action.equals(ACTION_STOP)) {
                    processStopRequest(false);
                }
            }
        }
    }

    return START_STICKY;
}

private void processTogglePlaybackRequest() {
    if (mState == MediaState.Paused || mState == MediaState.Stopped) {
        processPlayRequest();
    } else {
        processPauseRequest();
    }
}

private void processPlayRequest() {
    try {
        if (mState == MediaState.Stopped) {
            createMediaPlayerIfNeeded();
            mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            mPlayer.setDataSource(getApplicationContext(), Uri.parse(mCurrentUrl));
            mPlayer.prepare();

        } else if (mState == MediaState.Paused) {
            mState = MediaState.Playing;
            setUpAsForeground("Playing...");
            if (!mPlayer.isPlaying()) {
                mPlayer.start();

                if (mIMediaPlayer != null) {
                    mIMediaPlayer.onAudioPlay();
                }
            }
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

private void processPauseRequest() {
    if (mState == MediaState.Playing) {
        mState = MediaState.Paused;
        mPlayer.pause();
        relaxResources(false);

        if (mIMediaPlayer != null) {
            mIMediaPlayer.onAudioPause();
        }
    }
}

private void processStopRequest(boolean force) {
    if (mState == MediaState.Playing || mState == MediaState.Paused || force) {
        mState = MediaState.Stopped;
        relaxResources(true);
        stopSelf();
    }
}

private void createMediaPlayerIfNeeded() {
    if (mPlayer == null) {
        mPlayer = new MediaPlayer();
        mPlayer.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);
        mPlayer.setOnPreparedListener(this);
        mPlayer.setOnCompletionListener(this);
        mPlayer.setOnErrorListener(this);
    } else
        mPlayer.reset();
}

private void relaxResources(boolean releaseMediaPlayer) {
    stopForeground(true);

    if (releaseMediaPlayer && mPlayer != null) {
        mPlayer.reset();
        mPlayer.release();
        mPlayer = null;
    }
}

@Override
public boolean onError(MediaPlayer mp, int what, int extra) {
    Toast.makeText(getApplicationContext(), "Media player error! Resetting.", Toast.LENGTH_SHORT).show();
    Log.e("MusicPlayer", "Error: what=" + String.valueOf(what) + ", extra=" + String.valueOf(extra));

    mState = MediaState.Stopped;
    relaxResources(true);

    if (mIMediaPlayer != null) {
        mIMediaPlayer.onError();
    }
    return true; // true indicates we handled the error
}

@Override
public void onPrepared(MediaPlayer mp) {
    mState = MediaState.Playing;
    updateNotification("Playing...");
    if (!mPlayer.isPlaying()) {
        mPlayer.start();
        if (mIMediaPlayer != null) {
            mIMediaPlayer.onAudioPlay();
        }
    }
}

@Override
public void onCompletion(MediaPlayer mp) {
    mState = MediaState.Stopped;
    relaxResources(true);
    stopSelf();
    if (mIMediaPlayer != null) {
        mIMediaPlayer.onAudioStop();
    }
}

/**
 * Updates the notification.
 */
private void updateNotification(String text) {
    mNotificationManager.notify(NOTIFICATION_ID, buildNotification(text).build());
}

private void setUpAsForeground(String text) {
    startForeground(NOTIFICATION_ID, buildNotification(text).build());
}

private NotificationCompat.Builder buildNotification(String text) {
    NotificationCompat.Builder builder = new NotificationCompat.Builder(this.getApplicationContext());
    builder.setSmallIcon(R.drawable.ic_launcher)
            .setOngoing(true)
            .setContentTitle("Cyberinsane MusicPlayer")
            .setContentText(text)
            .setContentIntent(
                    PendingIntent.getActivity(getApplicationContext(), 0, new Intent(getApplicationContext(),
                            MediaPlayerActivity.class), PendingIntent.FLAG_UPDATE_CURRENT))
            .setContentInfo("Awesome");

    return builder;
}

@Override
public void onDestroy() {
    mState = MediaState.Stopped;
    relaxResources(true);
}

public class LocalBinder extends Binder {
    MediaPlayerService getService() {
        return MediaPlayerService.this;
    }
}

@Override
public IBinder onBind(Intent intent) {
    return mBinder;
}

private final IBinder mBinder = new LocalBinder();
private IMediaPlayer mIMediaPlayer;

public MediaPlayer getMediaPlayer() {
    return mPlayer;
}

public void setIMediaPlayer(IMediaPlayer mediaPlayer) {
    mIMediaPlayer = mediaPlayer;

}

public MediaState getMediaState() {
    return mState;
}

public boolean isPlaying() {
    return (mState == MediaState.Playing);
}

public String getCurrentUrl() {
    return mCurrentUrl;
}

public long duration() {
    if (mPlayer != null) {
        return mPlayer.getDuration();
    }
    return 0;
}

public long position() {
    if (mPlayer != null) {
        return mPlayer.getCurrentPosition();
    }
    return 0;
}

public void seekTo(long position) {
    if (mPlayer != null) {
        mPlayer.seekTo((int) position);
    }
}

}
package com.cyberinsane.musicplayerlibrary;

import java.io.File;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;

public class MediaPlayerActivity extends Activity implements IMediaPlayer {

private ImageButton mButtonPlay;
private EditText mEditTextUrl;
private SeekBar mSeekBarProgress;

private boolean mIsBound;
private String mExtStorePath;

private MediaPlayerService mMediaService;

private Handler mSeekHandler = new Handler();

private Runnable mSeekRunnable = new Runnable() {
    @Override
    public void run() {
        seekStartUpdation();
    }
};

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.media_player_activity);

    mButtonPlay = (ImageButton) findViewById(R.id.buttonPlay);
    mEditTextUrl = (EditText) findViewById(R.id.editTextURL);
    mSeekBarProgress = (SeekBar) findViewById(R.id.seekBarMediaProgress);
    mExtStorePath = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator;

    doBindService();
    initListeners();
}

private void initListeners() {
    mButtonPlay.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            String urlExt = mEditTextUrl.getText().toString();
            if (urlExt != null && !urlExt.equals("")) {
                String url = mExtStorePath + urlExt;
                startService(new Intent(MediaPlayerService.ACTION_TOGGLE_PLAYBACK).putExtra(
                        MediaPlayerService.INTENT_URL, url));
            }
        }
    });

    mSeekBarProgress.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
            mMediaService.seekTo(seekBar.getProgress());
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {
            // empty
        }

        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            // empty
        }
    });
}

@Override
protected void onResume() {
    super.onResume();
    doBindService();
}

@Override
protected void onDestroy() {
    super.onDestroy();
    doUnbindService();
}

@Override
protected void onPause() {
    super.onPause();
    doUnbindService();
}

private ServiceConnection mConnection = new ServiceConnection() {
    @Override
    public void onServiceConnected(ComponentName className, IBinder service) {
        mMediaService = ((MediaPlayerService.LocalBinder) service).getService();
        mMediaService.setIMediaPlayer(MediaPlayerActivity.this);
        setControlState();
    }

    @Override
    public void onServiceDisconnected(ComponentName className) {
        mMediaService = null;
    }
};

private void doBindService() {
    bindService(new Intent(MediaPlayerActivity.this, MediaPlayerService.class), mConnection,
            Context.BIND_AUTO_CREATE);
    mIsBound = true;
}

private void doUnbindService() {
    if (mIsBound) {
        unbindService(mConnection);
        mIsBound = false;
    }
}

@Override
public void onAudioPlay() {
    setPlayerState(true);
}

@Override
public void onAudioPause() {
    setPlayerState(false);
}

@Override
public void onAudioStop() {
    setPlayerState(false);
    mSeekBarProgress.setProgress(0);
}

@Override
public void onError() {
    // handle errors here
}

private void setControlState() {
    if (mMediaService.isPlaying()) {
        mEditTextUrl.setText(mMediaService.getCurrentUrl().replace(mExtStorePath, ""));
        setPlayerState(true);
    } else {
        setPlayerState(false);
    }
}

public void setPlayerState(boolean isPlaying) {
    if (isPlaying) {
        mButtonPlay.setImageResource(R.drawable.ic_pause);
        mSeekBarProgress.setMax((int) mMediaService.duration());
        seekStartUpdation();
    } else {
        mButtonPlay.setImageResource(R.drawable.ic_play);
        seekStopUpdate();
    }
}

public void seekStartUpdation() {
    mSeekBarProgress.setProgress((int) mMediaService.position());
    mSeekHandler.postDelayed(mSeekRunnable, 1000);
}

public void seekStopUpdate() {
    mSeekHandler.removeCallbacks(mSeekRunnable);
}
}
媒体播放器事件侦听器

package com.cyberinsane.musicplayerlibrary;

public interface IMediaPlayer {

public void onAudioPlay();

public void onAudioPause();

public void onAudioStop();

public void onError();

}
最后是我的清单文件

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.cyberinsane.musicplayerlibrary"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
    android:minSdkVersion="8"
    android:targetSdkVersion="18" />

<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name="com.cyberinsane.musicplayerlibrary.MediaPlayerActivity"
        android:label="@string/app_name"
        android:launchMode="singleTask" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <service
        android:name="com.cyberinsane.musicplayerlibrary.MediaPlayerService"
        android:exported="false" >
        <intent-filter>
            <action android:name="com.cyberinsane.musicplayerlibrary.action.TOGGLE_PLAYBACK" />
            <action android:name="com.cyberinsane.musicplayerlibrary.action.PLAY" />
            <action android:name="com.cyberinsane.musicplayerlibrary.action.PAUSE" />
            <action android:name="com.cyberinsane.musicplayerlibrary.action.SKIP" />
            <action android:name="com.cyberinsane.musicplayerlibrary.action.REWIND" />
            <action android:name="com.cyberinsane.musicplayerlibrary.action.STOP" />
        </intent-filter>
    </service>
</application>

</manifest>

当您关闭应用程序时,您的活动将被销毁,因此对您的媒体播放器变量的引用将丢失。当你重新创建你的活动时,你会得到一组新的引用,因此你无法停止它

您必须创建一个名为MediaPlayerService的服务,该服务将处理所有与媒体相关的操作,如播放、暂停等

您可以在此处阅读有关服务的信息:

如果您想要一个媒体播放器的示例,可以查看RandomMusicLayer,这是android在android示例项目中提供的一个优秀的媒体播放器示例

这是我对MediaPlayerService的实现

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.cyberinsane.musicplayerlibrary"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
    android:minSdkVersion="8"
    android:targetSdkVersion="18" />

<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name="com.cyberinsane.musicplayerlibrary.MediaPlayerActivity"
        android:label="@string/app_name"
        android:launchMode="singleTask" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <service
        android:name="com.cyberinsane.musicplayerlibrary.MediaPlayerService"
        android:exported="false" >
        <intent-filter>
            <action android:name="com.cyberinsane.musicplayerlibrary.action.TOGGLE_PLAYBACK" />
            <action android:name="com.cyberinsane.musicplayerlibrary.action.PLAY" />
            <action android:name="com.cyberinsane.musicplayerlibrary.action.PAUSE" />
            <action android:name="com.cyberinsane.musicplayerlibrary.action.SKIP" />
            <action android:name="com.cyberinsane.musicplayerlibrary.action.REWIND" />
            <action android:name="com.cyberinsane.musicplayerlibrary.action.STOP" />
        </intent-filter>
    </service>
</application>

</manifest>
MediaPlayerService类:

package com.cyberinsane.musicplayerlibrary;

import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnErrorListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.net.Uri;
import android.os.Binder;
import android.os.IBinder;
import android.os.PowerManager;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import android.widget.Toast;

public class MediaPlayerService extends Service implements OnCompletionListener, OnPreparedListener, OnErrorListener {

private static final int NOTIFICATION_ID = 1;
public static final String INTENT_URL = "url";

public enum MediaState {
    Playing, Paused, Stopped
}

private MediaState mState = MediaState.Stopped;
private MediaPlayer mPlayer;

private NotificationManager mNotificationManager;

public String mCurrentUrl = "";

public static final String ACTION_TOGGLE_PLAYBACK = "com.cyberinsane.musicplayerlibrary.action.TOGGLE_PLAYBACK";
public static final String ACTION_PLAY = "com.cyberinsane.musicplayerlibrary.action.PLAY";
public static final String ACTION_PAUSE = "com.cyberinsane.musicplayerlibrary.action.PAUSE";
public static final String ACTION_STOP = "com.cyberinsane.musicplayerlibrary.action.STOP";

@Override
public void onCreate() {
    super.onCreate();
    mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    if (intent != null) {
        String action = intent.getAction();
        String url = intent.getExtras().getString(INTENT_URL);
        if (url != null) {
            if (!url.equals(mCurrentUrl)) {
                mCurrentUrl = url;
                mState = MediaState.Stopped;
                relaxResources(true);
                processPlayRequest();
            } else {
                if (action.equals(ACTION_TOGGLE_PLAYBACK)) {
                    processTogglePlaybackRequest();
                } else if (action.equals(ACTION_PLAY)) {
                    processPlayRequest();
                } else if (action.equals(ACTION_PAUSE)) {
                    processPauseRequest();
                } else if (action.equals(ACTION_STOP)) {
                    processStopRequest(false);
                }
            }
        }
    }

    return START_STICKY;
}

private void processTogglePlaybackRequest() {
    if (mState == MediaState.Paused || mState == MediaState.Stopped) {
        processPlayRequest();
    } else {
        processPauseRequest();
    }
}

private void processPlayRequest() {
    try {
        if (mState == MediaState.Stopped) {
            createMediaPlayerIfNeeded();
            mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            mPlayer.setDataSource(getApplicationContext(), Uri.parse(mCurrentUrl));
            mPlayer.prepare();

        } else if (mState == MediaState.Paused) {
            mState = MediaState.Playing;
            setUpAsForeground("Playing...");
            if (!mPlayer.isPlaying()) {
                mPlayer.start();

                if (mIMediaPlayer != null) {
                    mIMediaPlayer.onAudioPlay();
                }
            }
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

private void processPauseRequest() {
    if (mState == MediaState.Playing) {
        mState = MediaState.Paused;
        mPlayer.pause();
        relaxResources(false);

        if (mIMediaPlayer != null) {
            mIMediaPlayer.onAudioPause();
        }
    }
}

private void processStopRequest(boolean force) {
    if (mState == MediaState.Playing || mState == MediaState.Paused || force) {
        mState = MediaState.Stopped;
        relaxResources(true);
        stopSelf();
    }
}

private void createMediaPlayerIfNeeded() {
    if (mPlayer == null) {
        mPlayer = new MediaPlayer();
        mPlayer.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);
        mPlayer.setOnPreparedListener(this);
        mPlayer.setOnCompletionListener(this);
        mPlayer.setOnErrorListener(this);
    } else
        mPlayer.reset();
}

private void relaxResources(boolean releaseMediaPlayer) {
    stopForeground(true);

    if (releaseMediaPlayer && mPlayer != null) {
        mPlayer.reset();
        mPlayer.release();
        mPlayer = null;
    }
}

@Override
public boolean onError(MediaPlayer mp, int what, int extra) {
    Toast.makeText(getApplicationContext(), "Media player error! Resetting.", Toast.LENGTH_SHORT).show();
    Log.e("MusicPlayer", "Error: what=" + String.valueOf(what) + ", extra=" + String.valueOf(extra));

    mState = MediaState.Stopped;
    relaxResources(true);

    if (mIMediaPlayer != null) {
        mIMediaPlayer.onError();
    }
    return true; // true indicates we handled the error
}

@Override
public void onPrepared(MediaPlayer mp) {
    mState = MediaState.Playing;
    updateNotification("Playing...");
    if (!mPlayer.isPlaying()) {
        mPlayer.start();
        if (mIMediaPlayer != null) {
            mIMediaPlayer.onAudioPlay();
        }
    }
}

@Override
public void onCompletion(MediaPlayer mp) {
    mState = MediaState.Stopped;
    relaxResources(true);
    stopSelf();
    if (mIMediaPlayer != null) {
        mIMediaPlayer.onAudioStop();
    }
}

/**
 * Updates the notification.
 */
private void updateNotification(String text) {
    mNotificationManager.notify(NOTIFICATION_ID, buildNotification(text).build());
}

private void setUpAsForeground(String text) {
    startForeground(NOTIFICATION_ID, buildNotification(text).build());
}

private NotificationCompat.Builder buildNotification(String text) {
    NotificationCompat.Builder builder = new NotificationCompat.Builder(this.getApplicationContext());
    builder.setSmallIcon(R.drawable.ic_launcher)
            .setOngoing(true)
            .setContentTitle("Cyberinsane MusicPlayer")
            .setContentText(text)
            .setContentIntent(
                    PendingIntent.getActivity(getApplicationContext(), 0, new Intent(getApplicationContext(),
                            MediaPlayerActivity.class), PendingIntent.FLAG_UPDATE_CURRENT))
            .setContentInfo("Awesome");

    return builder;
}

@Override
public void onDestroy() {
    mState = MediaState.Stopped;
    relaxResources(true);
}

public class LocalBinder extends Binder {
    MediaPlayerService getService() {
        return MediaPlayerService.this;
    }
}

@Override
public IBinder onBind(Intent intent) {
    return mBinder;
}

private final IBinder mBinder = new LocalBinder();
private IMediaPlayer mIMediaPlayer;

public MediaPlayer getMediaPlayer() {
    return mPlayer;
}

public void setIMediaPlayer(IMediaPlayer mediaPlayer) {
    mIMediaPlayer = mediaPlayer;

}

public MediaState getMediaState() {
    return mState;
}

public boolean isPlaying() {
    return (mState == MediaState.Playing);
}

public String getCurrentUrl() {
    return mCurrentUrl;
}

public long duration() {
    if (mPlayer != null) {
        return mPlayer.getDuration();
    }
    return 0;
}

public long position() {
    if (mPlayer != null) {
        return mPlayer.getCurrentPosition();
    }
    return 0;
}

public void seekTo(long position) {
    if (mPlayer != null) {
        mPlayer.seekTo((int) position);
    }
}

}
package com.cyberinsane.musicplayerlibrary;

import java.io.File;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;

public class MediaPlayerActivity extends Activity implements IMediaPlayer {

private ImageButton mButtonPlay;
private EditText mEditTextUrl;
private SeekBar mSeekBarProgress;

private boolean mIsBound;
private String mExtStorePath;

private MediaPlayerService mMediaService;

private Handler mSeekHandler = new Handler();

private Runnable mSeekRunnable = new Runnable() {
    @Override
    public void run() {
        seekStartUpdation();
    }
};

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.media_player_activity);

    mButtonPlay = (ImageButton) findViewById(R.id.buttonPlay);
    mEditTextUrl = (EditText) findViewById(R.id.editTextURL);
    mSeekBarProgress = (SeekBar) findViewById(R.id.seekBarMediaProgress);
    mExtStorePath = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator;

    doBindService();
    initListeners();
}

private void initListeners() {
    mButtonPlay.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            String urlExt = mEditTextUrl.getText().toString();
            if (urlExt != null && !urlExt.equals("")) {
                String url = mExtStorePath + urlExt;
                startService(new Intent(MediaPlayerService.ACTION_TOGGLE_PLAYBACK).putExtra(
                        MediaPlayerService.INTENT_URL, url));
            }
        }
    });

    mSeekBarProgress.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
            mMediaService.seekTo(seekBar.getProgress());
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {
            // empty
        }

        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            // empty
        }
    });
}

@Override
protected void onResume() {
    super.onResume();
    doBindService();
}

@Override
protected void onDestroy() {
    super.onDestroy();
    doUnbindService();
}

@Override
protected void onPause() {
    super.onPause();
    doUnbindService();
}

private ServiceConnection mConnection = new ServiceConnection() {
    @Override
    public void onServiceConnected(ComponentName className, IBinder service) {
        mMediaService = ((MediaPlayerService.LocalBinder) service).getService();
        mMediaService.setIMediaPlayer(MediaPlayerActivity.this);
        setControlState();
    }

    @Override
    public void onServiceDisconnected(ComponentName className) {
        mMediaService = null;
    }
};

private void doBindService() {
    bindService(new Intent(MediaPlayerActivity.this, MediaPlayerService.class), mConnection,
            Context.BIND_AUTO_CREATE);
    mIsBound = true;
}

private void doUnbindService() {
    if (mIsBound) {
        unbindService(mConnection);
        mIsBound = false;
    }
}

@Override
public void onAudioPlay() {
    setPlayerState(true);
}

@Override
public void onAudioPause() {
    setPlayerState(false);
}

@Override
public void onAudioStop() {
    setPlayerState(false);
    mSeekBarProgress.setProgress(0);
}

@Override
public void onError() {
    // handle errors here
}

private void setControlState() {
    if (mMediaService.isPlaying()) {
        mEditTextUrl.setText(mMediaService.getCurrentUrl().replace(mExtStorePath, ""));
        setPlayerState(true);
    } else {
        setPlayerState(false);
    }
}

public void setPlayerState(boolean isPlaying) {
    if (isPlaying) {
        mButtonPlay.setImageResource(R.drawable.ic_pause);
        mSeekBarProgress.setMax((int) mMediaService.duration());
        seekStartUpdation();
    } else {
        mButtonPlay.setImageResource(R.drawable.ic_play);
        seekStopUpdate();
    }
}

public void seekStartUpdation() {
    mSeekBarProgress.setProgress((int) mMediaService.position());
    mSeekHandler.postDelayed(mSeekRunnable, 1000);
}

public void seekStopUpdate() {
    mSeekHandler.removeCallbacks(mSeekRunnable);
}
}
MediaPlayerActivity类:

package com.cyberinsane.musicplayerlibrary;

import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnErrorListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.net.Uri;
import android.os.Binder;
import android.os.IBinder;
import android.os.PowerManager;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import android.widget.Toast;

public class MediaPlayerService extends Service implements OnCompletionListener, OnPreparedListener, OnErrorListener {

private static final int NOTIFICATION_ID = 1;
public static final String INTENT_URL = "url";

public enum MediaState {
    Playing, Paused, Stopped
}

private MediaState mState = MediaState.Stopped;
private MediaPlayer mPlayer;

private NotificationManager mNotificationManager;

public String mCurrentUrl = "";

public static final String ACTION_TOGGLE_PLAYBACK = "com.cyberinsane.musicplayerlibrary.action.TOGGLE_PLAYBACK";
public static final String ACTION_PLAY = "com.cyberinsane.musicplayerlibrary.action.PLAY";
public static final String ACTION_PAUSE = "com.cyberinsane.musicplayerlibrary.action.PAUSE";
public static final String ACTION_STOP = "com.cyberinsane.musicplayerlibrary.action.STOP";

@Override
public void onCreate() {
    super.onCreate();
    mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    if (intent != null) {
        String action = intent.getAction();
        String url = intent.getExtras().getString(INTENT_URL);
        if (url != null) {
            if (!url.equals(mCurrentUrl)) {
                mCurrentUrl = url;
                mState = MediaState.Stopped;
                relaxResources(true);
                processPlayRequest();
            } else {
                if (action.equals(ACTION_TOGGLE_PLAYBACK)) {
                    processTogglePlaybackRequest();
                } else if (action.equals(ACTION_PLAY)) {
                    processPlayRequest();
                } else if (action.equals(ACTION_PAUSE)) {
                    processPauseRequest();
                } else if (action.equals(ACTION_STOP)) {
                    processStopRequest(false);
                }
            }
        }
    }

    return START_STICKY;
}

private void processTogglePlaybackRequest() {
    if (mState == MediaState.Paused || mState == MediaState.Stopped) {
        processPlayRequest();
    } else {
        processPauseRequest();
    }
}

private void processPlayRequest() {
    try {
        if (mState == MediaState.Stopped) {
            createMediaPlayerIfNeeded();
            mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            mPlayer.setDataSource(getApplicationContext(), Uri.parse(mCurrentUrl));
            mPlayer.prepare();

        } else if (mState == MediaState.Paused) {
            mState = MediaState.Playing;
            setUpAsForeground("Playing...");
            if (!mPlayer.isPlaying()) {
                mPlayer.start();

                if (mIMediaPlayer != null) {
                    mIMediaPlayer.onAudioPlay();
                }
            }
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

private void processPauseRequest() {
    if (mState == MediaState.Playing) {
        mState = MediaState.Paused;
        mPlayer.pause();
        relaxResources(false);

        if (mIMediaPlayer != null) {
            mIMediaPlayer.onAudioPause();
        }
    }
}

private void processStopRequest(boolean force) {
    if (mState == MediaState.Playing || mState == MediaState.Paused || force) {
        mState = MediaState.Stopped;
        relaxResources(true);
        stopSelf();
    }
}

private void createMediaPlayerIfNeeded() {
    if (mPlayer == null) {
        mPlayer = new MediaPlayer();
        mPlayer.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);
        mPlayer.setOnPreparedListener(this);
        mPlayer.setOnCompletionListener(this);
        mPlayer.setOnErrorListener(this);
    } else
        mPlayer.reset();
}

private void relaxResources(boolean releaseMediaPlayer) {
    stopForeground(true);

    if (releaseMediaPlayer && mPlayer != null) {
        mPlayer.reset();
        mPlayer.release();
        mPlayer = null;
    }
}

@Override
public boolean onError(MediaPlayer mp, int what, int extra) {
    Toast.makeText(getApplicationContext(), "Media player error! Resetting.", Toast.LENGTH_SHORT).show();
    Log.e("MusicPlayer", "Error: what=" + String.valueOf(what) + ", extra=" + String.valueOf(extra));

    mState = MediaState.Stopped;
    relaxResources(true);

    if (mIMediaPlayer != null) {
        mIMediaPlayer.onError();
    }
    return true; // true indicates we handled the error
}

@Override
public void onPrepared(MediaPlayer mp) {
    mState = MediaState.Playing;
    updateNotification("Playing...");
    if (!mPlayer.isPlaying()) {
        mPlayer.start();
        if (mIMediaPlayer != null) {
            mIMediaPlayer.onAudioPlay();
        }
    }
}

@Override
public void onCompletion(MediaPlayer mp) {
    mState = MediaState.Stopped;
    relaxResources(true);
    stopSelf();
    if (mIMediaPlayer != null) {
        mIMediaPlayer.onAudioStop();
    }
}

/**
 * Updates the notification.
 */
private void updateNotification(String text) {
    mNotificationManager.notify(NOTIFICATION_ID, buildNotification(text).build());
}

private void setUpAsForeground(String text) {
    startForeground(NOTIFICATION_ID, buildNotification(text).build());
}

private NotificationCompat.Builder buildNotification(String text) {
    NotificationCompat.Builder builder = new NotificationCompat.Builder(this.getApplicationContext());
    builder.setSmallIcon(R.drawable.ic_launcher)
            .setOngoing(true)
            .setContentTitle("Cyberinsane MusicPlayer")
            .setContentText(text)
            .setContentIntent(
                    PendingIntent.getActivity(getApplicationContext(), 0, new Intent(getApplicationContext(),
                            MediaPlayerActivity.class), PendingIntent.FLAG_UPDATE_CURRENT))
            .setContentInfo("Awesome");

    return builder;
}

@Override
public void onDestroy() {
    mState = MediaState.Stopped;
    relaxResources(true);
}

public class LocalBinder extends Binder {
    MediaPlayerService getService() {
        return MediaPlayerService.this;
    }
}

@Override
public IBinder onBind(Intent intent) {
    return mBinder;
}

private final IBinder mBinder = new LocalBinder();
private IMediaPlayer mIMediaPlayer;

public MediaPlayer getMediaPlayer() {
    return mPlayer;
}

public void setIMediaPlayer(IMediaPlayer mediaPlayer) {
    mIMediaPlayer = mediaPlayer;

}

public MediaState getMediaState() {
    return mState;
}

public boolean isPlaying() {
    return (mState == MediaState.Playing);
}

public String getCurrentUrl() {
    return mCurrentUrl;
}

public long duration() {
    if (mPlayer != null) {
        return mPlayer.getDuration();
    }
    return 0;
}

public long position() {
    if (mPlayer != null) {
        return mPlayer.getCurrentPosition();
    }
    return 0;
}

public void seekTo(long position) {
    if (mPlayer != null) {
        mPlayer.seekTo((int) position);
    }
}

}
package com.cyberinsane.musicplayerlibrary;

import java.io.File;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;

public class MediaPlayerActivity extends Activity implements IMediaPlayer {

private ImageButton mButtonPlay;
private EditText mEditTextUrl;
private SeekBar mSeekBarProgress;

private boolean mIsBound;
private String mExtStorePath;

private MediaPlayerService mMediaService;

private Handler mSeekHandler = new Handler();

private Runnable mSeekRunnable = new Runnable() {
    @Override
    public void run() {
        seekStartUpdation();
    }
};

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.media_player_activity);

    mButtonPlay = (ImageButton) findViewById(R.id.buttonPlay);
    mEditTextUrl = (EditText) findViewById(R.id.editTextURL);
    mSeekBarProgress = (SeekBar) findViewById(R.id.seekBarMediaProgress);
    mExtStorePath = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator;

    doBindService();
    initListeners();
}

private void initListeners() {
    mButtonPlay.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            String urlExt = mEditTextUrl.getText().toString();
            if (urlExt != null && !urlExt.equals("")) {
                String url = mExtStorePath + urlExt;
                startService(new Intent(MediaPlayerService.ACTION_TOGGLE_PLAYBACK).putExtra(
                        MediaPlayerService.INTENT_URL, url));
            }
        }
    });

    mSeekBarProgress.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
            mMediaService.seekTo(seekBar.getProgress());
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {
            // empty
        }

        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            // empty
        }
    });
}

@Override
protected void onResume() {
    super.onResume();
    doBindService();
}

@Override
protected void onDestroy() {
    super.onDestroy();
    doUnbindService();
}

@Override
protected void onPause() {
    super.onPause();
    doUnbindService();
}

private ServiceConnection mConnection = new ServiceConnection() {
    @Override
    public void onServiceConnected(ComponentName className, IBinder service) {
        mMediaService = ((MediaPlayerService.LocalBinder) service).getService();
        mMediaService.setIMediaPlayer(MediaPlayerActivity.this);
        setControlState();
    }

    @Override
    public void onServiceDisconnected(ComponentName className) {
        mMediaService = null;
    }
};

private void doBindService() {
    bindService(new Intent(MediaPlayerActivity.this, MediaPlayerService.class), mConnection,
            Context.BIND_AUTO_CREATE);
    mIsBound = true;
}

private void doUnbindService() {
    if (mIsBound) {
        unbindService(mConnection);
        mIsBound = false;
    }
}

@Override
public void onAudioPlay() {
    setPlayerState(true);
}

@Override
public void onAudioPause() {
    setPlayerState(false);
}

@Override
public void onAudioStop() {
    setPlayerState(false);
    mSeekBarProgress.setProgress(0);
}

@Override
public void onError() {
    // handle errors here
}

private void setControlState() {
    if (mMediaService.isPlaying()) {
        mEditTextUrl.setText(mMediaService.getCurrentUrl().replace(mExtStorePath, ""));
        setPlayerState(true);
    } else {
        setPlayerState(false);
    }
}

public void setPlayerState(boolean isPlaying) {
    if (isPlaying) {
        mButtonPlay.setImageResource(R.drawable.ic_pause);
        mSeekBarProgress.setMax((int) mMediaService.duration());
        seekStartUpdation();
    } else {
        mButtonPlay.setImageResource(R.drawable.ic_play);
        seekStopUpdate();
    }
}

public void seekStartUpdation() {
    mSeekBarProgress.setProgress((int) mMediaService.position());
    mSeekHandler.postDelayed(mSeekRunnable, 1000);
}

public void seekStopUpdate() {
    mSeekHandler.removeCallbacks(mSeekRunnable);
}
}
媒体播放器事件侦听器

package com.cyberinsane.musicplayerlibrary;

public interface IMediaPlayer {

public void onAudioPlay();

public void onAudioPause();

public void onAudioStop();

public void onError();

}
最后是我的清单文件

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.cyberinsane.musicplayerlibrary"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
    android:minSdkVersion="8"
    android:targetSdkVersion="18" />

<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name="com.cyberinsane.musicplayerlibrary.MediaPlayerActivity"
        android:label="@string/app_name"
        android:launchMode="singleTask" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <service
        android:name="com.cyberinsane.musicplayerlibrary.MediaPlayerService"
        android:exported="false" >
        <intent-filter>
            <action android:name="com.cyberinsane.musicplayerlibrary.action.TOGGLE_PLAYBACK" />
            <action android:name="com.cyberinsane.musicplayerlibrary.action.PLAY" />
            <action android:name="com.cyberinsane.musicplayerlibrary.action.PAUSE" />
            <action android:name="com.cyberinsane.musicplayerlibrary.action.SKIP" />
            <action android:name="com.cyberinsane.musicplayerlibrary.action.REWIND" />
            <action android:name="com.cyberinsane.musicplayerlibrary.action.STOP" />
        </intent-filter>
    </service>
</application>

</manifest>

当您关闭应用程序时,您的活动将被销毁,因此对您的媒体播放器变量的引用将丢失。当你重新创建你的活动时,你会得到一组新的引用,因此你无法停止它

您必须创建一个名为MediaPlayerService的服务,该服务将处理所有与媒体相关的操作,如播放、暂停等

您可以在此处阅读有关服务的信息:

如果您想要一个媒体播放器的示例,可以查看RandomMusicLayer,这是android在android示例项目中提供的一个优秀的媒体播放器示例

这是我对MediaPlayerService的实现

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.cyberinsane.musicplayerlibrary"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
    android:minSdkVersion="8"
    android:targetSdkVersion="18" />

<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name="com.cyberinsane.musicplayerlibrary.MediaPlayerActivity"
        android:label="@string/app_name"
        android:launchMode="singleTask" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <service
        android:name="com.cyberinsane.musicplayerlibrary.MediaPlayerService"
        android:exported="false" >
        <intent-filter>
            <action android:name="com.cyberinsane.musicplayerlibrary.action.TOGGLE_PLAYBACK" />
            <action android:name="com.cyberinsane.musicplayerlibrary.action.PLAY" />
            <action android:name="com.cyberinsane.musicplayerlibrary.action.PAUSE" />
            <action android:name="com.cyberinsane.musicplayerlibrary.action.SKIP" />
            <action android:name="com.cyberinsane.musicplayerlibrary.action.REWIND" />
            <action android:name="com.cyberinsane.musicplayerlibrary.action.STOP" />
        </intent-filter>
    </service>
</application>

</manifest>
MediaPlayerService类:

package com.cyberinsane.musicplayerlibrary;

import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnErrorListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.net.Uri;
import android.os.Binder;
import android.os.IBinder;
import android.os.PowerManager;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import android.widget.Toast;

public class MediaPlayerService extends Service implements OnCompletionListener, OnPreparedListener, OnErrorListener {

private static final int NOTIFICATION_ID = 1;
public static final String INTENT_URL = "url";

public enum MediaState {
    Playing, Paused, Stopped
}

private MediaState mState = MediaState.Stopped;
private MediaPlayer mPlayer;

private NotificationManager mNotificationManager;

public String mCurrentUrl = "";

public static final String ACTION_TOGGLE_PLAYBACK = "com.cyberinsane.musicplayerlibrary.action.TOGGLE_PLAYBACK";
public static final String ACTION_PLAY = "com.cyberinsane.musicplayerlibrary.action.PLAY";
public static final String ACTION_PAUSE = "com.cyberinsane.musicplayerlibrary.action.PAUSE";
public static final String ACTION_STOP = "com.cyberinsane.musicplayerlibrary.action.STOP";

@Override
public void onCreate() {
    super.onCreate();
    mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    if (intent != null) {
        String action = intent.getAction();
        String url = intent.getExtras().getString(INTENT_URL);
        if (url != null) {
            if (!url.equals(mCurrentUrl)) {
                mCurrentUrl = url;
                mState = MediaState.Stopped;
                relaxResources(true);
                processPlayRequest();
            } else {
                if (action.equals(ACTION_TOGGLE_PLAYBACK)) {
                    processTogglePlaybackRequest();
                } else if (action.equals(ACTION_PLAY)) {
                    processPlayRequest();
                } else if (action.equals(ACTION_PAUSE)) {
                    processPauseRequest();
                } else if (action.equals(ACTION_STOP)) {
                    processStopRequest(false);
                }
            }
        }
    }

    return START_STICKY;
}

private void processTogglePlaybackRequest() {
    if (mState == MediaState.Paused || mState == MediaState.Stopped) {
        processPlayRequest();
    } else {
        processPauseRequest();
    }
}

private void processPlayRequest() {
    try {
        if (mState == MediaState.Stopped) {
            createMediaPlayerIfNeeded();
            mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            mPlayer.setDataSource(getApplicationContext(), Uri.parse(mCurrentUrl));
            mPlayer.prepare();

        } else if (mState == MediaState.Paused) {
            mState = MediaState.Playing;
            setUpAsForeground("Playing...");
            if (!mPlayer.isPlaying()) {
                mPlayer.start();

                if (mIMediaPlayer != null) {
                    mIMediaPlayer.onAudioPlay();
                }
            }
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

private void processPauseRequest() {
    if (mState == MediaState.Playing) {
        mState = MediaState.Paused;
        mPlayer.pause();
        relaxResources(false);

        if (mIMediaPlayer != null) {
            mIMediaPlayer.onAudioPause();
        }
    }
}

private void processStopRequest(boolean force) {
    if (mState == MediaState.Playing || mState == MediaState.Paused || force) {
        mState = MediaState.Stopped;
        relaxResources(true);
        stopSelf();
    }
}

private void createMediaPlayerIfNeeded() {
    if (mPlayer == null) {
        mPlayer = new MediaPlayer();
        mPlayer.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);
        mPlayer.setOnPreparedListener(this);
        mPlayer.setOnCompletionListener(this);
        mPlayer.setOnErrorListener(this);
    } else
        mPlayer.reset();
}

private void relaxResources(boolean releaseMediaPlayer) {
    stopForeground(true);

    if (releaseMediaPlayer && mPlayer != null) {
        mPlayer.reset();
        mPlayer.release();
        mPlayer = null;
    }
}

@Override
public boolean onError(MediaPlayer mp, int what, int extra) {
    Toast.makeText(getApplicationContext(), "Media player error! Resetting.", Toast.LENGTH_SHORT).show();
    Log.e("MusicPlayer", "Error: what=" + String.valueOf(what) + ", extra=" + String.valueOf(extra));

    mState = MediaState.Stopped;
    relaxResources(true);

    if (mIMediaPlayer != null) {
        mIMediaPlayer.onError();
    }
    return true; // true indicates we handled the error
}

@Override
public void onPrepared(MediaPlayer mp) {
    mState = MediaState.Playing;
    updateNotification("Playing...");
    if (!mPlayer.isPlaying()) {
        mPlayer.start();
        if (mIMediaPlayer != null) {
            mIMediaPlayer.onAudioPlay();
        }
    }
}

@Override
public void onCompletion(MediaPlayer mp) {
    mState = MediaState.Stopped;
    relaxResources(true);
    stopSelf();
    if (mIMediaPlayer != null) {
        mIMediaPlayer.onAudioStop();
    }
}

/**
 * Updates the notification.
 */
private void updateNotification(String text) {
    mNotificationManager.notify(NOTIFICATION_ID, buildNotification(text).build());
}

private void setUpAsForeground(String text) {
    startForeground(NOTIFICATION_ID, buildNotification(text).build());
}

private NotificationCompat.Builder buildNotification(String text) {
    NotificationCompat.Builder builder = new NotificationCompat.Builder(this.getApplicationContext());
    builder.setSmallIcon(R.drawable.ic_launcher)
            .setOngoing(true)
            .setContentTitle("Cyberinsane MusicPlayer")
            .setContentText(text)
            .setContentIntent(
                    PendingIntent.getActivity(getApplicationContext(), 0, new Intent(getApplicationContext(),
                            MediaPlayerActivity.class), PendingIntent.FLAG_UPDATE_CURRENT))
            .setContentInfo("Awesome");

    return builder;
}

@Override
public void onDestroy() {
    mState = MediaState.Stopped;
    relaxResources(true);
}

public class LocalBinder extends Binder {
    MediaPlayerService getService() {
        return MediaPlayerService.this;
    }
}

@Override
public IBinder onBind(Intent intent) {
    return mBinder;
}

private final IBinder mBinder = new LocalBinder();
private IMediaPlayer mIMediaPlayer;

public MediaPlayer getMediaPlayer() {
    return mPlayer;
}

public void setIMediaPlayer(IMediaPlayer mediaPlayer) {
    mIMediaPlayer = mediaPlayer;

}

public MediaState getMediaState() {
    return mState;
}

public boolean isPlaying() {
    return (mState == MediaState.Playing);
}

public String getCurrentUrl() {
    return mCurrentUrl;
}

public long duration() {
    if (mPlayer != null) {
        return mPlayer.getDuration();
    }
    return 0;
}

public long position() {
    if (mPlayer != null) {
        return mPlayer.getCurrentPosition();
    }
    return 0;
}

public void seekTo(long position) {
    if (mPlayer != null) {
        mPlayer.seekTo((int) position);
    }
}

}
package com.cyberinsane.musicplayerlibrary;

import java.io.File;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;

public class MediaPlayerActivity extends Activity implements IMediaPlayer {

private ImageButton mButtonPlay;
private EditText mEditTextUrl;
private SeekBar mSeekBarProgress;

private boolean mIsBound;
private String mExtStorePath;

private MediaPlayerService mMediaService;

private Handler mSeekHandler = new Handler();

private Runnable mSeekRunnable = new Runnable() {
    @Override
    public void run() {
        seekStartUpdation();
    }
};

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.media_player_activity);

    mButtonPlay = (ImageButton) findViewById(R.id.buttonPlay);
    mEditTextUrl = (EditText) findViewById(R.id.editTextURL);
    mSeekBarProgress = (SeekBar) findViewById(R.id.seekBarMediaProgress);
    mExtStorePath = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator;

    doBindService();
    initListeners();
}

private void initListeners() {
    mButtonPlay.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            String urlExt = mEditTextUrl.getText().toString();
            if (urlExt != null && !urlExt.equals("")) {
                String url = mExtStorePath + urlExt;
                startService(new Intent(MediaPlayerService.ACTION_TOGGLE_PLAYBACK).putExtra(
                        MediaPlayerService.INTENT_URL, url));
            }
        }
    });

    mSeekBarProgress.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
            mMediaService.seekTo(seekBar.getProgress());
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {
            // empty
        }

        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            // empty
        }
    });
}

@Override
protected void onResume() {
    super.onResume();
    doBindService();
}

@Override
protected void onDestroy() {
    super.onDestroy();
    doUnbindService();
}

@Override
protected void onPause() {
    super.onPause();
    doUnbindService();
}

private ServiceConnection mConnection = new ServiceConnection() {
    @Override
    public void onServiceConnected(ComponentName className, IBinder service) {
        mMediaService = ((MediaPlayerService.LocalBinder) service).getService();
        mMediaService.setIMediaPlayer(MediaPlayerActivity.this);
        setControlState();
    }

    @Override
    public void onServiceDisconnected(ComponentName className) {
        mMediaService = null;
    }
};

private void doBindService() {
    bindService(new Intent(MediaPlayerActivity.this, MediaPlayerService.class), mConnection,
            Context.BIND_AUTO_CREATE);
    mIsBound = true;
}

private void doUnbindService() {
    if (mIsBound) {
        unbindService(mConnection);
        mIsBound = false;
    }
}

@Override
public void onAudioPlay() {
    setPlayerState(true);
}

@Override
public void onAudioPause() {
    setPlayerState(false);
}

@Override
public void onAudioStop() {
    setPlayerState(false);
    mSeekBarProgress.setProgress(0);
}

@Override
public void onError() {
    // handle errors here
}

private void setControlState() {
    if (mMediaService.isPlaying()) {
        mEditTextUrl.setText(mMediaService.getCurrentUrl().replace(mExtStorePath, ""));
        setPlayerState(true);
    } else {
        setPlayerState(false);
    }
}

public void setPlayerState(boolean isPlaying) {
    if (isPlaying) {
        mButtonPlay.setImageResource(R.drawable.ic_pause);
        mSeekBarProgress.setMax((int) mMediaService.duration());
        seekStartUpdation();
    } else {
        mButtonPlay.setImageResource(R.drawable.ic_play);
        seekStopUpdate();
    }
}

public void seekStartUpdation() {
    mSeekBarProgress.setProgress((int) mMediaService.position());
    mSeekHandler.postDelayed(mSeekRunnable, 1000);
}

public void seekStopUpdate() {
    mSeekHandler.removeCallbacks(mSeekRunnable);
}
}
MediaPlayerActivity类:

package com.cyberinsane.musicplayerlibrary;

import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnErrorListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.net.Uri;
import android.os.Binder;
import android.os.IBinder;
import android.os.PowerManager;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import android.widget.Toast;

public class MediaPlayerService extends Service implements OnCompletionListener, OnPreparedListener, OnErrorListener {

private static final int NOTIFICATION_ID = 1;
public static final String INTENT_URL = "url";

public enum MediaState {
    Playing, Paused, Stopped
}

private MediaState mState = MediaState.Stopped;
private MediaPlayer mPlayer;

private NotificationManager mNotificationManager;

public String mCurrentUrl = "";

public static final String ACTION_TOGGLE_PLAYBACK = "com.cyberinsane.musicplayerlibrary.action.TOGGLE_PLAYBACK";
public static final String ACTION_PLAY = "com.cyberinsane.musicplayerlibrary.action.PLAY";
public static final String ACTION_PAUSE = "com.cyberinsane.musicplayerlibrary.action.PAUSE";
public static final String ACTION_STOP = "com.cyberinsane.musicplayerlibrary.action.STOP";

@Override
public void onCreate() {
    super.onCreate();
    mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    if (intent != null) {
        String action = intent.getAction();
        String url = intent.getExtras().getString(INTENT_URL);
        if (url != null) {
            if (!url.equals(mCurrentUrl)) {
                mCurrentUrl = url;
                mState = MediaState.Stopped;
                relaxResources(true);
                processPlayRequest();
            } else {
                if (action.equals(ACTION_TOGGLE_PLAYBACK)) {
                    processTogglePlaybackRequest();
                } else if (action.equals(ACTION_PLAY)) {
                    processPlayRequest();
                } else if (action.equals(ACTION_PAUSE)) {
                    processPauseRequest();
                } else if (action.equals(ACTION_STOP)) {
                    processStopRequest(false);
                }
            }
        }
    }

    return START_STICKY;
}

private void processTogglePlaybackRequest() {
    if (mState == MediaState.Paused || mState == MediaState.Stopped) {
        processPlayRequest();
    } else {
        processPauseRequest();
    }
}

private void processPlayRequest() {
    try {
        if (mState == MediaState.Stopped) {
            createMediaPlayerIfNeeded();
            mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            mPlayer.setDataSource(getApplicationContext(), Uri.parse(mCurrentUrl));
            mPlayer.prepare();

        } else if (mState == MediaState.Paused) {
            mState = MediaState.Playing;
            setUpAsForeground("Playing...");
            if (!mPlayer.isPlaying()) {
                mPlayer.start();

                if (mIMediaPlayer != null) {
                    mIMediaPlayer.onAudioPlay();
                }
            }
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

private void processPauseRequest() {
    if (mState == MediaState.Playing) {
        mState = MediaState.Paused;
        mPlayer.pause();
        relaxResources(false);

        if (mIMediaPlayer != null) {
            mIMediaPlayer.onAudioPause();
        }
    }
}

private void processStopRequest(boolean force) {
    if (mState == MediaState.Playing || mState == MediaState.Paused || force) {
        mState = MediaState.Stopped;
        relaxResources(true);
        stopSelf();
    }
}

private void createMediaPlayerIfNeeded() {
    if (mPlayer == null) {
        mPlayer = new MediaPlayer();
        mPlayer.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);
        mPlayer.setOnPreparedListener(this);
        mPlayer.setOnCompletionListener(this);
        mPlayer.setOnErrorListener(this);
    } else
        mPlayer.reset();
}

private void relaxResources(boolean releaseMediaPlayer) {
    stopForeground(true);

    if (releaseMediaPlayer && mPlayer != null) {
        mPlayer.reset();
        mPlayer.release();
        mPlayer = null;
    }
}

@Override
public boolean onError(MediaPlayer mp, int what, int extra) {
    Toast.makeText(getApplicationContext(), "Media player error! Resetting.", Toast.LENGTH_SHORT).show();
    Log.e("MusicPlayer", "Error: what=" + String.valueOf(what) + ", extra=" + String.valueOf(extra));

    mState = MediaState.Stopped;
    relaxResources(true);

    if (mIMediaPlayer != null) {
        mIMediaPlayer.onError();
    }
    return true; // true indicates we handled the error
}

@Override
public void onPrepared(MediaPlayer mp) {
    mState = MediaState.Playing;
    updateNotification("Playing...");
    if (!mPlayer.isPlaying()) {
        mPlayer.start();
        if (mIMediaPlayer != null) {
            mIMediaPlayer.onAudioPlay();
        }
    }
}

@Override
public void onCompletion(MediaPlayer mp) {
    mState = MediaState.Stopped;
    relaxResources(true);
    stopSelf();
    if (mIMediaPlayer != null) {
        mIMediaPlayer.onAudioStop();
    }
}

/**
 * Updates the notification.
 */
private void updateNotification(String text) {
    mNotificationManager.notify(NOTIFICATION_ID, buildNotification(text).build());
}

private void setUpAsForeground(String text) {
    startForeground(NOTIFICATION_ID, buildNotification(text).build());
}

private NotificationCompat.Builder buildNotification(String text) {
    NotificationCompat.Builder builder = new NotificationCompat.Builder(this.getApplicationContext());
    builder.setSmallIcon(R.drawable.ic_launcher)
            .setOngoing(true)
            .setContentTitle("Cyberinsane MusicPlayer")
            .setContentText(text)
            .setContentIntent(
                    PendingIntent.getActivity(getApplicationContext(), 0, new Intent(getApplicationContext(),
                            MediaPlayerActivity.class), PendingIntent.FLAG_UPDATE_CURRENT))
            .setContentInfo("Awesome");

    return builder;
}

@Override
public void onDestroy() {
    mState = MediaState.Stopped;
    relaxResources(true);
}

public class LocalBinder extends Binder {
    MediaPlayerService getService() {
        return MediaPlayerService.this;
    }
}

@Override
public IBinder onBind(Intent intent) {
    return mBinder;
}

private final IBinder mBinder = new LocalBinder();
private IMediaPlayer mIMediaPlayer;

public MediaPlayer getMediaPlayer() {
    return mPlayer;
}

public void setIMediaPlayer(IMediaPlayer mediaPlayer) {
    mIMediaPlayer = mediaPlayer;

}

public MediaState getMediaState() {
    return mState;
}

public boolean isPlaying() {
    return (mState == MediaState.Playing);
}

public String getCurrentUrl() {
    return mCurrentUrl;
}

public long duration() {
    if (mPlayer != null) {
        return mPlayer.getDuration();
    }
    return 0;
}

public long position() {
    if (mPlayer != null) {
        return mPlayer.getCurrentPosition();
    }
    return 0;
}

public void seekTo(long position) {
    if (mPlayer != null) {
        mPlayer.seekTo((int) position);
    }
}

}
package com.cyberinsane.musicplayerlibrary;

import java.io.File;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;

public class MediaPlayerActivity extends Activity implements IMediaPlayer {

private ImageButton mButtonPlay;
private EditText mEditTextUrl;
private SeekBar mSeekBarProgress;

private boolean mIsBound;
private String mExtStorePath;

private MediaPlayerService mMediaService;

private Handler mSeekHandler = new Handler();

private Runnable mSeekRunnable = new Runnable() {
    @Override
    public void run() {
        seekStartUpdation();
    }
};

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.media_player_activity);

    mButtonPlay = (ImageButton) findViewById(R.id.buttonPlay);
    mEditTextUrl = (EditText) findViewById(R.id.editTextURL);
    mSeekBarProgress = (SeekBar) findViewById(R.id.seekBarMediaProgress);
    mExtStorePath = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator;

    doBindService();
    initListeners();
}

private void initListeners() {
    mButtonPlay.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            String urlExt = mEditTextUrl.getText().toString();
            if (urlExt != null && !urlExt.equals("")) {
                String url = mExtStorePath + urlExt;
                startService(new Intent(MediaPlayerService.ACTION_TOGGLE_PLAYBACK).putExtra(
                        MediaPlayerService.INTENT_URL, url));
            }
        }
    });

    mSeekBarProgress.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
            mMediaService.seekTo(seekBar.getProgress());
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {
            // empty
        }

        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            // empty
        }
    });
}

@Override
protected void onResume() {
    super.onResume();
    doBindService();
}

@Override
protected void onDestroy() {
    super.onDestroy();
    doUnbindService();
}

@Override
protected void onPause() {
    super.onPause();
    doUnbindService();
}

private ServiceConnection mConnection = new ServiceConnection() {
    @Override
    public void onServiceConnected(ComponentName className, IBinder service) {
        mMediaService = ((MediaPlayerService.LocalBinder) service).getService();
        mMediaService.setIMediaPlayer(MediaPlayerActivity.this);
        setControlState();
    }

    @Override
    public void onServiceDisconnected(ComponentName className) {
        mMediaService = null;
    }
};

private void doBindService() {
    bindService(new Intent(MediaPlayerActivity.this, MediaPlayerService.class), mConnection,
            Context.BIND_AUTO_CREATE);
    mIsBound = true;
}

private void doUnbindService() {
    if (mIsBound) {
        unbindService(mConnection);
        mIsBound = false;
    }
}

@Override
public void onAudioPlay() {
    setPlayerState(true);
}

@Override
public void onAudioPause() {
    setPlayerState(false);
}

@Override
public void onAudioStop() {
    setPlayerState(false);
    mSeekBarProgress.setProgress(0);
}

@Override
public void onError() {
    // handle errors here
}

private void setControlState() {
    if (mMediaService.isPlaying()) {
        mEditTextUrl.setText(mMediaService.getCurrentUrl().replace(mExtStorePath, ""));
        setPlayerState(true);
    } else {
        setPlayerState(false);
    }
}

public void setPlayerState(boolean isPlaying) {
    if (isPlaying) {
        mButtonPlay.setImageResource(R.drawable.ic_pause);
        mSeekBarProgress.setMax((int) mMediaService.duration());
        seekStartUpdation();
    } else {
        mButtonPlay.setImageResource(R.drawable.ic_play);
        seekStopUpdate();
    }
}

public void seekStartUpdation() {
    mSeekBarProgress.setProgress((int) mMediaService.position());
    mSeekHandler.postDelayed(mSeekRunnable, 1000);
}

public void seekStopUpdate() {
    mSeekHandler.removeCallbacks(mSeekRunnable);
}
}
媒体播放器事件侦听器

package com.cyberinsane.musicplayerlibrary;

public interface IMediaPlayer {

public void onAudioPlay();

public void onAudioPause();

public void onAudioStop();

public void onError();

}
最后是我的清单文件

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.cyberinsane.musicplayerlibrary"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
    android:minSdkVersion="8"
    android:targetSdkVersion="18" />

<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name="com.cyberinsane.musicplayerlibrary.MediaPlayerActivity"
        android:label="@string/app_name"
        android:launchMode="singleTask" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <service
        android:name="com.cyberinsane.musicplayerlibrary.MediaPlayerService"
        android:exported="false" >
        <intent-filter>
            <action android:name="com.cyberinsane.musicplayerlibrary.action.TOGGLE_PLAYBACK" />
            <action android:name="com.cyberinsane.musicplayerlibrary.action.PLAY" />
            <action android:name="com.cyberinsane.musicplayerlibrary.action.PAUSE" />
            <action android:name="com.cyberinsane.musicplayerlibrary.action.SKIP" />
            <action android:name="com.cyberinsane.musicplayerlibrary.action.REWIND" />
            <action android:name="com.cyberinsane.musicplayerlibrary.action.STOP" />
        </intent-filter>
    </service>
</application>

</manifest>

当您关闭应用程序时,您的活动将被销毁,因此对您的媒体播放器变量的引用将丢失。当你重新创建你的活动时,你会得到一组新的引用,因此你无法停止它

您必须创建一个名为MediaPlayerService的服务,该服务将处理所有与媒体相关的操作,如播放、暂停等

您可以在此处阅读有关服务的信息:

如果您想要一个媒体播放器的示例,可以查看RandomMusicLayer,这是android在android示例项目中提供的一个优秀的媒体播放器示例

这是我对MediaPlayerService的实现

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.cyberinsane.musicplayerlibrary"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
    android:minSdkVersion="8"
    android:targetSdkVersion="18" />

<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name="com.cyberinsane.musicplayerlibrary.MediaPlayerActivity"
        android:label="@string/app_name"
        android:launchMode="singleTask" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <service
        android:name="com.cyberinsane.musicplayerlibrary.MediaPlayerService"
        android:exported="false" >
        <intent-filter>
            <action android:name="com.cyberinsane.musicplayerlibrary.action.TOGGLE_PLAYBACK" />
            <action android:name="com.cyberinsane.musicplayerlibrary.action.PLAY" />
            <action android:name="com.cyberinsane.musicplayerlibrary.action.PAUSE" />
            <action android:name="com.cyberinsane.musicplayerlibrary.action.SKIP" />
            <action android:name="com.cyberinsane.musicplayerlibrary.action.REWIND" />
            <action android:name="com.cyberinsane.musicplayerlibrary.action.STOP" />
        </intent-filter>
    </service>
</application>

</manifest>
MediaPlayerService类:

package com.cyberinsane.musicplayerlibrary;

import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnErrorListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.net.Uri;
import android.os.Binder;
import android.os.IBinder;
import android.os.PowerManager;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import android.widget.Toast;

public class MediaPlayerService extends Service implements OnCompletionListener, OnPreparedListener, OnErrorListener {

private static final int NOTIFICATION_ID = 1;
public static final String INTENT_URL = "url";

public enum MediaState {
    Playing, Paused, Stopped
}

private MediaState mState = MediaState.Stopped;
private MediaPlayer mPlayer;

private NotificationManager mNotificationManager;

public String mCurrentUrl = "";

public static final String ACTION_TOGGLE_PLAYBACK = "com.cyberinsane.musicplayerlibrary.action.TOGGLE_PLAYBACK";
public static final String ACTION_PLAY = "com.cyberinsane.musicplayerlibrary.action.PLAY";
public static final String ACTION_PAUSE = "com.cyberinsane.musicplayerlibrary.action.PAUSE";
public static final String ACTION_STOP = "com.cyberinsane.musicplayerlibrary.action.STOP";

@Override
public void onCreate() {
    super.onCreate();
    mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    if (intent != null) {
        String action = intent.getAction();
        String url = intent.getExtras().getString(INTENT_URL);
        if (url != null) {
            if (!url.equals(mCurrentUrl)) {
                mCurrentUrl = url;
                mState = MediaState.Stopped;
                relaxResources(true);
                processPlayRequest();
            } else {
                if (action.equals(ACTION_TOGGLE_PLAYBACK)) {
                    processTogglePlaybackRequest();
                } else if (action.equals(ACTION_PLAY)) {
                    processPlayRequest();
                } else if (action.equals(ACTION_PAUSE)) {
                    processPauseRequest();
                } else if (action.equals(ACTION_STOP)) {
                    processStopRequest(false);
                }
            }
        }
    }

    return START_STICKY;
}

private void processTogglePlaybackRequest() {
    if (mState == MediaState.Paused || mState == MediaState.Stopped) {
        processPlayRequest();
    } else {
        processPauseRequest();
    }
}

private void processPlayRequest() {
    try {
        if (mState == MediaState.Stopped) {
            createMediaPlayerIfNeeded();
            mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            mPlayer.setDataSource(getApplicationContext(), Uri.parse(mCurrentUrl));
            mPlayer.prepare();

        } else if (mState == MediaState.Paused) {
            mState = MediaState.Playing;
            setUpAsForeground("Playing...");
            if (!mPlayer.isPlaying()) {
                mPlayer.start();

                if (mIMediaPlayer != null) {
                    mIMediaPlayer.onAudioPlay();
                }
            }
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

private void processPauseRequest() {
    if (mState == MediaState.Playing) {
        mState = MediaState.Paused;
        mPlayer.pause();
        relaxResources(false);

        if (mIMediaPlayer != null) {
            mIMediaPlayer.onAudioPause();
        }
    }
}

private void processStopRequest(boolean force) {
    if (mState == MediaState.Playing || mState == MediaState.Paused || force) {
        mState = MediaState.Stopped;
        relaxResources(true);
        stopSelf();
    }
}

private void createMediaPlayerIfNeeded() {
    if (mPlayer == null) {
        mPlayer = new MediaPlayer();
        mPlayer.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);
        mPlayer.setOnPreparedListener(this);
        mPlayer.setOnCompletionListener(this);
        mPlayer.setOnErrorListener(this);
    } else
        mPlayer.reset();
}

private void relaxResources(boolean releaseMediaPlayer) {
    stopForeground(true);

    if (releaseMediaPlayer && mPlayer != null) {
        mPlayer.reset();
        mPlayer.release();
        mPlayer = null;
    }
}

@Override
public boolean onError(MediaPlayer mp, int what, int extra) {
    Toast.makeText(getApplicationContext(), "Media player error! Resetting.", Toast.LENGTH_SHORT).show();
    Log.e("MusicPlayer", "Error: what=" + String.valueOf(what) + ", extra=" + String.valueOf(extra));

    mState = MediaState.Stopped;
    relaxResources(true);

    if (mIMediaPlayer != null) {
        mIMediaPlayer.onError();
    }
    return true; // true indicates we handled the error
}

@Override
public void onPrepared(MediaPlayer mp) {
    mState = MediaState.Playing;
    updateNotification("Playing...");
    if (!mPlayer.isPlaying()) {
        mPlayer.start();
        if (mIMediaPlayer != null) {
            mIMediaPlayer.onAudioPlay();
        }
    }
}

@Override
public void onCompletion(MediaPlayer mp) {
    mState = MediaState.Stopped;
    relaxResources(true);
    stopSelf();
    if (mIMediaPlayer != null) {
        mIMediaPlayer.onAudioStop();
    }
}

/**
 * Updates the notification.
 */
private void updateNotification(String text) {
    mNotificationManager.notify(NOTIFICATION_ID, buildNotification(text).build());
}

private void setUpAsForeground(String text) {
    startForeground(NOTIFICATION_ID, buildNotification(text).build());
}

private NotificationCompat.Builder buildNotification(String text) {
    NotificationCompat.Builder builder = new NotificationCompat.Builder(this.getApplicationContext());
    builder.setSmallIcon(R.drawable.ic_launcher)
            .setOngoing(true)
            .setContentTitle("Cyberinsane MusicPlayer")
            .setContentText(text)
            .setContentIntent(
                    PendingIntent.getActivity(getApplicationContext(), 0, new Intent(getApplicationContext(),
                            MediaPlayerActivity.class), PendingIntent.FLAG_UPDATE_CURRENT))
            .setContentInfo("Awesome");

    return builder;
}

@Override
public void onDestroy() {
    mState = MediaState.Stopped;
    relaxResources(true);
}

public class LocalBinder extends Binder {
    MediaPlayerService getService() {
        return MediaPlayerService.this;
    }
}

@Override
public IBinder onBind(Intent intent) {
    return mBinder;
}

private final IBinder mBinder = new LocalBinder();
private IMediaPlayer mIMediaPlayer;

public MediaPlayer getMediaPlayer() {
    return mPlayer;
}

public void setIMediaPlayer(IMediaPlayer mediaPlayer) {
    mIMediaPlayer = mediaPlayer;

}

public MediaState getMediaState() {
    return mState;
}

public boolean isPlaying() {
    return (mState == MediaState.Playing);
}

public String getCurrentUrl() {
    return mCurrentUrl;
}

public long duration() {
    if (mPlayer != null) {
        return mPlayer.getDuration();
    }
    return 0;
}

public long position() {
    if (mPlayer != null) {
        return mPlayer.getCurrentPosition();
    }
    return 0;
}

public void seekTo(long position) {
    if (mPlayer != null) {
        mPlayer.seekTo((int) position);
    }
}

}
package com.cyberinsane.musicplayerlibrary;

import java.io.File;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;

public class MediaPlayerActivity extends Activity implements IMediaPlayer {

private ImageButton mButtonPlay;
private EditText mEditTextUrl;
private SeekBar mSeekBarProgress;

private boolean mIsBound;
private String mExtStorePath;

private MediaPlayerService mMediaService;

private Handler mSeekHandler = new Handler();

private Runnable mSeekRunnable = new Runnable() {
    @Override
    public void run() {
        seekStartUpdation();
    }
};

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.media_player_activity);

    mButtonPlay = (ImageButton) findViewById(R.id.buttonPlay);
    mEditTextUrl = (EditText) findViewById(R.id.editTextURL);
    mSeekBarProgress = (SeekBar) findViewById(R.id.seekBarMediaProgress);
    mExtStorePath = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator;

    doBindService();
    initListeners();
}

private void initListeners() {
    mButtonPlay.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            String urlExt = mEditTextUrl.getText().toString();
            if (urlExt != null && !urlExt.equals("")) {
                String url = mExtStorePath + urlExt;
                startService(new Intent(MediaPlayerService.ACTION_TOGGLE_PLAYBACK).putExtra(
                        MediaPlayerService.INTENT_URL, url));
            }
        }
    });

    mSeekBarProgress.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
            mMediaService.seekTo(seekBar.getProgress());
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {
            // empty
        }

        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            // empty
        }
    });
}

@Override
protected void onResume() {
    super.onResume();
    doBindService();
}

@Override
protected void onDestroy() {
    super.onDestroy();
    doUnbindService();
}

@Override
protected void onPause() {
    super.onPause();
    doUnbindService();
}

private ServiceConnection mConnection = new ServiceConnection() {
    @Override
    public void onServiceConnected(ComponentName className, IBinder service) {
        mMediaService = ((MediaPlayerService.LocalBinder) service).getService();
        mMediaService.setIMediaPlayer(MediaPlayerActivity.this);
        setControlState();
    }

    @Override
    public void onServiceDisconnected(ComponentName className) {
        mMediaService = null;
    }
};

private void doBindService() {
    bindService(new Intent(MediaPlayerActivity.this, MediaPlayerService.class), mConnection,
            Context.BIND_AUTO_CREATE);
    mIsBound = true;
}

private void doUnbindService() {
    if (mIsBound) {
        unbindService(mConnection);
        mIsBound = false;
    }
}

@Override
public void onAudioPlay() {
    setPlayerState(true);
}

@Override
public void onAudioPause() {
    setPlayerState(false);
}

@Override
public void onAudioStop() {
    setPlayerState(false);
    mSeekBarProgress.setProgress(0);
}

@Override
public void onError() {
    // handle errors here
}

private void setControlState() {
    if (mMediaService.isPlaying()) {
        mEditTextUrl.setText(mMediaService.getCurrentUrl().replace(mExtStorePath, ""));
        setPlayerState(true);
    } else {
        setPlayerState(false);
    }
}

public void setPlayerState(boolean isPlaying) {
    if (isPlaying) {
        mButtonPlay.setImageResource(R.drawable.ic_pause);
        mSeekBarProgress.setMax((int) mMediaService.duration());
        seekStartUpdation();
    } else {
        mButtonPlay.setImageResource(R.drawable.ic_play);
        seekStopUpdate();
    }
}

public void seekStartUpdation() {
    mSeekBarProgress.setProgress((int) mMediaService.position());
    mSeekHandler.postDelayed(mSeekRunnable, 1000);
}

public void seekStopUpdate() {
    mSeekHandler.removeCallbacks(mSeekRunnable);
}
}
MediaPlayerActivity类:

package com.cyberinsane.musicplayerlibrary;

import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnErrorListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.net.Uri;
import android.os.Binder;
import android.os.IBinder;
import android.os.PowerManager;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import android.widget.Toast;

public class MediaPlayerService extends Service implements OnCompletionListener, OnPreparedListener, OnErrorListener {

private static final int NOTIFICATION_ID = 1;
public static final String INTENT_URL = "url";

public enum MediaState {
    Playing, Paused, Stopped
}

private MediaState mState = MediaState.Stopped;
private MediaPlayer mPlayer;

private NotificationManager mNotificationManager;

public String mCurrentUrl = "";

public static final String ACTION_TOGGLE_PLAYBACK = "com.cyberinsane.musicplayerlibrary.action.TOGGLE_PLAYBACK";
public static final String ACTION_PLAY = "com.cyberinsane.musicplayerlibrary.action.PLAY";
public static final String ACTION_PAUSE = "com.cyberinsane.musicplayerlibrary.action.PAUSE";
public static final String ACTION_STOP = "com.cyberinsane.musicplayerlibrary.action.STOP";

@Override
public void onCreate() {
    super.onCreate();
    mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    if (intent != null) {
        String action = intent.getAction();
        String url = intent.getExtras().getString(INTENT_URL);
        if (url != null) {
            if (!url.equals(mCurrentUrl)) {
                mCurrentUrl = url;
                mState = MediaState.Stopped;
                relaxResources(true);
                processPlayRequest();
            } else {
                if (action.equals(ACTION_TOGGLE_PLAYBACK)) {
                    processTogglePlaybackRequest();
                } else if (action.equals(ACTION_PLAY)) {
                    processPlayRequest();
                } else if (action.equals(ACTION_PAUSE)) {
                    processPauseRequest();
                } else if (action.equals(ACTION_STOP)) {
                    processStopRequest(false);
                }
            }
        }
    }

    return START_STICKY;
}

private void processTogglePlaybackRequest() {
    if (mState == MediaState.Paused || mState == MediaState.Stopped) {
        processPlayRequest();
    } else {
        processPauseRequest();
    }
}

private void processPlayRequest() {
    try {
        if (mState == MediaState.Stopped) {
            createMediaPlayerIfNeeded();
            mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            mPlayer.setDataSource(getApplicationContext(), Uri.parse(mCurrentUrl));
            mPlayer.prepare();

        } else if (mState == MediaState.Paused) {
            mState = MediaState.Playing;
            setUpAsForeground("Playing...");
            if (!mPlayer.isPlaying()) {
                mPlayer.start();

                if (mIMediaPlayer != null) {
                    mIMediaPlayer.onAudioPlay();
                }
            }
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

private void processPauseRequest() {
    if (mState == MediaState.Playing) {
        mState = MediaState.Paused;
        mPlayer.pause();
        relaxResources(false);

        if (mIMediaPlayer != null) {
            mIMediaPlayer.onAudioPause();
        }
    }
}

private void processStopRequest(boolean force) {
    if (mState == MediaState.Playing || mState == MediaState.Paused || force) {
        mState = MediaState.Stopped;
        relaxResources(true);
        stopSelf();
    }
}

private void createMediaPlayerIfNeeded() {
    if (mPlayer == null) {
        mPlayer = new MediaPlayer();
        mPlayer.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);
        mPlayer.setOnPreparedListener(this);
        mPlayer.setOnCompletionListener(this);
        mPlayer.setOnErrorListener(this);
    } else
        mPlayer.reset();
}

private void relaxResources(boolean releaseMediaPlayer) {
    stopForeground(true);

    if (releaseMediaPlayer && mPlayer != null) {
        mPlayer.reset();
        mPlayer.release();
        mPlayer = null;
    }
}

@Override
public boolean onError(MediaPlayer mp, int what, int extra) {
    Toast.makeText(getApplicationContext(), "Media player error! Resetting.", Toast.LENGTH_SHORT).show();
    Log.e("MusicPlayer", "Error: what=" + String.valueOf(what) + ", extra=" + String.valueOf(extra));

    mState = MediaState.Stopped;
    relaxResources(true);

    if (mIMediaPlayer != null) {
        mIMediaPlayer.onError();
    }
    return true; // true indicates we handled the error
}

@Override
public void onPrepared(MediaPlayer mp) {
    mState = MediaState.Playing;
    updateNotification("Playing...");
    if (!mPlayer.isPlaying()) {
        mPlayer.start();
        if (mIMediaPlayer != null) {
            mIMediaPlayer.onAudioPlay();
        }
    }
}

@Override
public void onCompletion(MediaPlayer mp) {
    mState = MediaState.Stopped;
    relaxResources(true);
    stopSelf();
    if (mIMediaPlayer != null) {
        mIMediaPlayer.onAudioStop();
    }
}

/**
 * Updates the notification.
 */
private void updateNotification(String text) {
    mNotificationManager.notify(NOTIFICATION_ID, buildNotification(text).build());
}

private void setUpAsForeground(String text) {
    startForeground(NOTIFICATION_ID, buildNotification(text).build());
}

private NotificationCompat.Builder buildNotification(String text) {
    NotificationCompat.Builder builder = new NotificationCompat.Builder(this.getApplicationContext());
    builder.setSmallIcon(R.drawable.ic_launcher)
            .setOngoing(true)
            .setContentTitle("Cyberinsane MusicPlayer")
            .setContentText(text)
            .setContentIntent(
                    PendingIntent.getActivity(getApplicationContext(), 0, new Intent(getApplicationContext(),
                            MediaPlayerActivity.class), PendingIntent.FLAG_UPDATE_CURRENT))
            .setContentInfo("Awesome");

    return builder;
}

@Override
public void onDestroy() {
    mState = MediaState.Stopped;
    relaxResources(true);
}

public class LocalBinder extends Binder {
    MediaPlayerService getService() {
        return MediaPlayerService.this;
    }
}

@Override
public IBinder onBind(Intent intent) {
    return mBinder;
}

private final IBinder mBinder = new LocalBinder();
private IMediaPlayer mIMediaPlayer;

public MediaPlayer getMediaPlayer() {
    return mPlayer;
}

public void setIMediaPlayer(IMediaPlayer mediaPlayer) {
    mIMediaPlayer = mediaPlayer;

}

public MediaState getMediaState() {
    return mState;
}

public boolean isPlaying() {
    return (mState == MediaState.Playing);
}

public String getCurrentUrl() {
    return mCurrentUrl;
}

public long duration() {
    if (mPlayer != null) {
        return mPlayer.getDuration();
    }
    return 0;
}

public long position() {
    if (mPlayer != null) {
        return mPlayer.getCurrentPosition();
    }
    return 0;
}

public void seekTo(long position) {
    if (mPlayer != null) {
        mPlayer.seekTo((int) position);
    }
}

}
package com.cyberinsane.musicplayerlibrary;

import java.io.File;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;

public class MediaPlayerActivity extends Activity implements IMediaPlayer {

private ImageButton mButtonPlay;
private EditText mEditTextUrl;
private SeekBar mSeekBarProgress;

private boolean mIsBound;
private String mExtStorePath;

private MediaPlayerService mMediaService;

private Handler mSeekHandler = new Handler();

private Runnable mSeekRunnable = new Runnable() {
    @Override
    public void run() {
        seekStartUpdation();
    }
};

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.media_player_activity);

    mButtonPlay = (ImageButton) findViewById(R.id.buttonPlay);
    mEditTextUrl = (EditText) findViewById(R.id.editTextURL);
    mSeekBarProgress = (SeekBar) findViewById(R.id.seekBarMediaProgress);
    mExtStorePath = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator;

    doBindService();
    initListeners();
}

private void initListeners() {
    mButtonPlay.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            String urlExt = mEditTextUrl.getText().toString();
            if (urlExt != null && !urlExt.equals("")) {
                String url = mExtStorePath + urlExt;
                startService(new Intent(MediaPlayerService.ACTION_TOGGLE_PLAYBACK).putExtra(
                        MediaPlayerService.INTENT_URL, url));
            }
        }
    });

    mSeekBarProgress.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
            mMediaService.seekTo(seekBar.getProgress());
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {
            // empty
        }

        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            // empty
        }
    });
}

@Override
protected void onResume() {
    super.onResume();
    doBindService();
}

@Override
protected void onDestroy() {
    super.onDestroy();
    doUnbindService();
}

@Override
protected void onPause() {
    super.onPause();
    doUnbindService();
}

private ServiceConnection mConnection = new ServiceConnection() {
    @Override
    public void onServiceConnected(ComponentName className, IBinder service) {
        mMediaService = ((MediaPlayerService.LocalBinder) service).getService();
        mMediaService.setIMediaPlayer(MediaPlayerActivity.this);
        setControlState();
    }

    @Override
    public void onServiceDisconnected(ComponentName className) {
        mMediaService = null;
    }
};

private void doBindService() {
    bindService(new Intent(MediaPlayerActivity.this, MediaPlayerService.class), mConnection,
            Context.BIND_AUTO_CREATE);
    mIsBound = true;
}

private void doUnbindService() {
    if (mIsBound) {
        unbindService(mConnection);
        mIsBound = false;
    }
}

@Override
public void onAudioPlay() {
    setPlayerState(true);
}

@Override
public void onAudioPause() {
    setPlayerState(false);
}

@Override
public void onAudioStop() {
    setPlayerState(false);
    mSeekBarProgress.setProgress(0);
}

@Override
public void onError() {
    // handle errors here
}

private void setControlState() {
    if (mMediaService.isPlaying()) {
        mEditTextUrl.setText(mMediaService.getCurrentUrl().replace(mExtStorePath, ""));
        setPlayerState(true);
    } else {
        setPlayerState(false);
    }
}

public void setPlayerState(boolean isPlaying) {
    if (isPlaying) {
        mButtonPlay.setImageResource(R.drawable.ic_pause);
        mSeekBarProgress.setMax((int) mMediaService.duration());
        seekStartUpdation();
    } else {
        mButtonPlay.setImageResource(R.drawable.ic_play);
        seekStopUpdate();
    }
}

public void seekStartUpdation() {
    mSeekBarProgress.setProgress((int) mMediaService.position());
    mSeekHandler.postDelayed(mSeekRunnable, 1000);
}

public void seekStopUpdate() {
    mSeekHandler.removeCallbacks(mSeekRunnable);
}
}
媒体播放器事件侦听器

package com.cyberinsane.musicplayerlibrary;

public interface IMediaPlayer {

public void onAudioPlay();

public void onAudioPause();

public void onAudioStop();

public void onError();

}
最后是我的清单文件

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.cyberinsane.musicplayerlibrary"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
    android:minSdkVersion="8"
    android:targetSdkVersion="18" />

<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name="com.cyberinsane.musicplayerlibrary.MediaPlayerActivity"
        android:label="@string/app_name"
        android:launchMode="singleTask" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <service
        android:name="com.cyberinsane.musicplayerlibrary.MediaPlayerService"
        android:exported="false" >
        <intent-filter>
            <action android:name="com.cyberinsane.musicplayerlibrary.action.TOGGLE_PLAYBACK" />
            <action android:name="com.cyberinsane.musicplayerlibrary.action.PLAY" />
            <action android:name="com.cyberinsane.musicplayerlibrary.action.PAUSE" />
            <action android:name="com.cyberinsane.musicplayerlibrary.action.SKIP" />
            <action android:name="com.cyberinsane.musicplayerlibrary.action.REWIND" />
            <action android:name="com.cyberinsane.musicplayerlibrary.action.STOP" />
        </intent-filter>
    </service>
</application>

</manifest>


您能帮我实现Mediaplayerservice吗。如果您已经从Android Sdk管理器下载了示例,请首先查看RandomMusicLayerFirst的链接。如果你让他们下载了goto Files>New>Projects>Android>Android示例项目,在这里你可以找到RandomMusicLayerTanks,嗨,我是Android新手。我已经创建了一个媒体播放器,可以播放、停止服务中的音乐。现在我想从搜索栏控制音乐的节奏。我试图在服务中实现seek bar。如何在服务中实现搜索栏,或者如何将搜索栏进度从主要活动更新到服务,提前感谢。对不起,我不知道如何更改媒体播放器的速度。你完全可以用另一个问题问这个问题。如果我的答案对你有任何帮助,请投赞成票或接受正确答案。你能帮我实现Mediaplayerservice吗。如果您已经从Android Sdk管理器下载了示例,请首先查看RandomMusicLayerFirst的链接。如果你让他们下载了goto Files>New>Projects>Android>Android示例项目,在这里你可以找到RandomMusicLayerTanks,嗨,我是Android新手。我创作了一部媒体剧