package com.czp;
import java.io.File;
import android.app.Service;
import android.content.Intent;
import android.content.SharedPreferences;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnErrorListener;
import android.os.IBinder;
public class MusicServer extends Service implements OnCompletionListener,OnErrorListener{
private MediaPlayer mp;
@Override
public void onStart(Intent intent, int startId) {
if(!mp.isPlaying())
{
mp.start();
}
mp.setOnCompletionListener(this);
mp.setOnErrorListener(this);
super.onStart(intent, startId);
}
@Override
public void onCreate() {
try {
SharedPreferences sp = Util.getSharedPreferences(this);
String userSettingMusicPath = sp.getString(Util.USER_MUSIC_PATH,"");
if(!userSettingMusicPath.isEmpty())
{
File f = new File(userSettingMusicPath);
if(f.exists())
{
mp = new MediaPlayer();
mp.setDataSource(userSettingMusicPath);
}
}
if(mp==null)
{
mp = MediaPlayer.create(this, R.raw.defaultMusicId);
}
mp.prepare();
} catch (Exception e) {
processError(e);
}
super.onCreate();
}
@Override
public void onDestroy() {
mp.stop();
mp.release();
mp = null;
super.onDestroy();
}
@Override
public IBinder onBind(Intent intent) {
return super.onBind(intent);
}
@Override
public void onCompletion(MediaPlayer mp) {
}
@Override
public boolean onError(MediaPlayer mp, int what, int extra) {
mp.stop();
mp.release();
return false;
}
/**
* 记录异常
* @param e
*/
private void processError(Exception e) {
}
}
package com.czp;
import android.app.Service;
import android.content.SharedPreferences;
public class Util {
private static final int MODE_WORLD_WRITEABLE = 0;
private static final String SHAER_FILE = "userSetting";
public static final String USER_MUSIC_PATH = "userMusicPath";
public static final String USER_LAST_LOACTION="userLastLocation";
public static SharedPreferences getSharedPreferences(Service server) {
return server.getSharedPreferences(SHAER_FILE, MODE_WORLD_WRITEABLE);
}
}
android 音乐播放service
最新推荐文章于 2018-12-28 10:59:18 发布