我有一项服务,其中我使用处理程序每毫秒获取媒体播放器的时间。
但是,当我的服务未绑定到任何活动时,我想从 onUnbind() 的处理程序中删除回调;服务的方法。
当服务绑定到一个活动时,我想通过在 Rebind/onBind() 上发布相同的回调来重用我的处理程序;
但是,它不起作用。需要帮忙!
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;
import androidx.annotation.Nullable;
import androidx.lifecycle.MutableLiveData;
import java.io.IOException;
public class MediaService extends Service {
private static final String TAG = "MediaService";
IBinder myBinder = new MyBinder();
MediaPlayer mediaPlayer = new MediaPlayer();
boolean isPrepared = false;
MutableLiveData<Integer> currrentTime = new MutableLiveData<>();
MutableLiveData<Integer> mediaPlayerDuration = new MutableLiveData<>();
private Handler handlerTime;
@Nullable
@Override
public IBinder onBind(Intent intent) {
handlerTime = new Handler();
//readyTime method posts delayed runnable on the handler @recurring
readyTime();
return myBinder;
}
@Override
public boolean onUnbind(Intent intent) {
handlerTime.removeCallbacks(curTimeRunnable);
return super.onUnbind(intent);
}
@Override
public void onCreate() {
super.onCreate();
Log.d(TAG, "onCreate: MediaService Created");
}
class MyBinder extends Binder {
MediaService getService() {
return MediaService.this;
}
}
public void setPathAndPlay(String path) {
isPrepared = false;
mediaPlayer.reset();
try {
mediaPlayer.setDataSource(path);
mediaPlayer.prepareAsync();
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
@Override
public void onPrepared(MediaPlayer mp) {
isPrepared = true;
mp.start();
mediaPlayerDuration.postValue(mediaPlayer.getDuration());
}
});
} catch (IOException e) {
Log.d(TAG, "setPathAndPlay: Error");
e.printStackTrace();
}
}
public boolean isMediaPlaying() {
return this.mediaPlayer.isPlaying();
}
public void pause() {
mediaPlayer.pause();
}
public void resume() {
try {
mediaPlayer.start();
} catch (Exception e) {
}
}
public void seekTo(int millis) {
mediaPlayer.seekTo(millis);
}
public int getTimeTotal() {
return mediaPlayer.getDuration();
}
public int getCurrentPos() {
return mediaPlayer.getCurrentPosition();
}
Runnable curTimeRunnable = new Runnable() {
@Override
public void run() {
currrentTime.postValue(mediaPlayer.getCurrentPosition());
Log.d(TAG, "run: VALUE POSTED");
if (handlerTime != null) {
handlerTime.postDelayed(this, 1);
}
}
};
public void readyTime() {
if (handlerTime != null) {
handlerTime.postDelayed(curTimeRunnable, 1);
}
}
}