私はで遊んでいMediaPlayerます。ユーザーがアクティビティを離れたときに音楽を再生したい。ただし、アクティビティを離れてアクティビティに戻ると、同じインスタンスにバインドしていないように見えます。
これは私のコードです:
public class MusicService extends Service {
private NotificationManager mNM;
public class LocalBinder extends Binder {
MusicService getService() {
return MusicService.this;
}
}
@Override
public void onCreate() {
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}
@Override
public void onDestroy() {
// Cancel the persistent notification.
// Tell the user we stopped.
Toast.makeText(this, "destroyed", Toast.LENGTH_SHORT).show();
}
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
// This is the object that receives interactions from clients. See
// RemoteService for a more complete example.
private final IBinder mBinder = new LocalBinder();
public void showtoast(int i){
Toast.makeText(this, "showtoast"+i, Toast.LENGTH_SHORT).show();
}
//Music player functions
String path = "http://mp3stream";
MediaPlayer mp;
Boolean mpLoaded=false;
public void play(){
if(!mpLoaded){
try {
mp=new MediaPlayer();
mp.setDataSource(path);
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
mp.prepareAsync();
mp.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
mp.start();
}
});
mpLoaded=true;
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void pause(){
if(mpLoaded){
mp.stop();
mpLoaded=false;
}
}
}
アクティビティを終了しない場合は問題なく動作しますが、終了しても音楽が再生されている場合は、戻って[停止]をクリックしても何も起こりません。再生ボタンを押すと、別のストリームが開始されます。
デバッガーはmpLoaded、サービスを聞くことができても、それがfalseであることを示しています。
これが私がそれをバインドする方法です。
private MusicService mBoundService;
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
mBoundService = ((MusicService.LocalBinder)service).getService();
mIsBound=true;
Toast.makeText(Main.this, "service connected", Toast.LENGTH_SHORT).show();
}
public void onServiceDisconnected(ComponentName className) {
mBoundService = null;
Toast.makeText(Main.this, "service disconnected", Toast.LENGTH_SHORT).show();
}
};
void doBindService() {
bindService(new Intent(getApplicationContext(), MusicService.class), mConnection, Context.BIND_AUTO_CREATE);
mIsBound = true;
}