我正在使用services编写音乐播放器示例。我能够通过使用其他应用程序中的活动来启动和停止服务。但现在我需要暂停播放器。我可以这样做,因为它们不是服务中的暂停方法
答案 0 :(得分:0)
利用:pause();
重启:prepare() 启动()
**LocalService.java** public class LocalService extends Service {
private NotificationManager mNM;
MediaPlayer mMediaPlayer;
private final IBinder mBinder = new LocalBinder();
public class LocalBinder extends Binder {
LocalService getService() {
return LocalService.this;
}
}
@Override
public void onCreate() {
mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
}
@Override
public void onDestroy() {
mNM.cancel(R.string.local_service_started);
Toast.makeText(this, R.string.local_service_stopped, Toast.LENGTH_SHORT).show();
}
public void startMp3Player() {
mMediaPlayer = MediaPlayer.create(getApplicationContext(),
R.raw.abc);
mMediaPlayer.start();
}
public void mp3Stop() {
mMediaPlayer.stop();
mMediaPlayer.release();
}
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
}
**LocalServiceBinding.JAVA** public class LocalServiceBinding extends Activity {
private boolean mIsBound;
private LocalService mBoundService;
Button mPlayButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.local_service_binding);
Button button = (Button)findViewById(R.id.bind);
button.setOnClickListener(mBindListener);
button = (Button)findViewById(R.id.unbind);
button.setOnClickListener(mUnbindListener);
mPlayButton = (Button)findViewById(R.id.play);
mPlayButton.setOnClickListener(mPlayListener);
mPlayButton.setText("Play");
mPlayButton.setEnabled(false);
}
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
mBoundService = ((LocalService.LocalBinder)service).getService();
Toast.makeText(LocalServiceBinding.this, R.string.local_service_connected,
Toast.LENGTH_SHORT).show();
}
public void onServiceDisconnected(ComponentName className) {
mBoundService = null;
Toast.makeText(LocalServiceBinding.this, R.string.local_service_disconnected,
Toast.LENGTH_SHORT).show();
}
};
private OnClickListener mBindListener = new OnClickListener() {
public void onClick(View v) {
bindService(new Intent(LocalServiceBinding.this,
LocalService.class), mConnection, Context.BIND_AUTO_CREATE);
mIsBound = true;
mPlayButton.setEnabled(true);
}
};
private OnClickListener mPlayListener = new OnClickListener() {
public void onClick(View v) {
if(mPlayButton.getText() == "Play")
{
mBoundService.startMp3Player();
mPlayButton.setText("Stop");
}
else
{
mBoundService.mp3Stop();
mPlayButton.setText("Play");
}
}
};
private OnClickListener mUnbindListener = new OnClickListener() {
public void onClick(View v) {
if (mIsBound) {
unbindService(mConnection);
mIsBound = false;
mPlayButton.setEnabled(false);
}
}
};
}