在我的应用程序中,我使用Service播放MediaPlayer,以更新SeekBar 我在服务
中做了计时器任务timer = new Timer();
timer.scheduleAtFixedRate(new RemindTask(), 0, 1 * 1000);
class RemindTask extends TimerTask {
@Override
public void run() {
if (mediaPlayer!=null && mediaPlayer.isPlaying()){
MusicPlayerActivity.progress=mediaPlayer.getCurrentPosition();
MusicPlayerActivity.total=mediaPlayer.getDuration();
}
}
}
并使用runnable list我在活动页面中创建了一个run方法,
@Override
public void run()
{
runOnUiThread(new Runnable() {
@Override
public void run() {
seekBar.setMax(total);
seekBar.setProgress(progress);
}
});
}
但我的问题是应用程序非常缓慢而且卡住了。
答案 0 :(得分:4)
使用BroadcastReceiver
将搜索栏表单服务更新为活动
在活动中添加广播以更新搜索栏
BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
//do something based on the intent's action
// UPDATE YOUR UI FROM HERE
}
};
在下面的活动中注册接收器
@Override
protected void onResume() {
super.onResume();
registerReceiver(receiver, filter);
}
@Override
protected void onPause() {
super.onPause();
unregisterReceiver(receiver);
}
从您的服务发送广播 - >在您的服务中添加以下代码以进行广播
Intent intent = new Intent();
intent.setAction("android.mybroadcast");
this.context.sendBroadcast(intent);
在意图中传递数据 - >搜索栏的整数值:)
答案 1 :(得分:1)
投入使用以更新搜索变量(全局和静态变量)的值
#Check for files that do not contain the language string
RewriteCond %{REQUEST_URI} !^/[a-z]{2}/.*
RewriteRule ^(.*)$ $1?lang=en [QSA,L]
#Capture the language string and present it as the variable
RewriteCond %{REQUEST_URI} ^/([a-z]{2})/(.*)
RewriteRule ^.* %2?lang=%1 [QSA,L]
在您的活动中:
private final Handler handler = new Handler(){
@Override
public void handleMessage(Message msg){
// update the seek variable here
}
};
答案 2 :(得分:0)
如果您需要为活动通信提供服务,请使用绑定服务 check it here。或者使用EventBus
等库答案 3 :(得分:-1)
您可以在https://github.com/googlesamples/android-UniversalMusicPlayer/blob/master/mobile/src/main/java/com/example/android/uamp/ui/FullScreenPlayerActivity.java中的android-UniversalMusicPlayer参考实现中找到有效的解决方案。
该概念涉及在MediaSession实例上设置当前位置,然后轮询MediaController以获取更改+计算当前位置:
private void updateProgress() {
if (mLastPlaybackState == null) {
return;
}
long currentPosition = mLastPlaybackState.getPosition();
if (mLastPlaybackState.getState() != PlaybackState.STATE_PAUSED) {
// Calculate the elapsed time between the last position update and now and unless
// paused, we can assume (delta * speed) + current position is approximately the
// latest position. This ensure that we do not repeatedly call the getPlaybackState()
// on MediaController.
long timeDelta = SystemClock.elapsedRealtime() -
mLastPlaybackState.getLastPositionUpdateTime();
currentPosition += (int) timeDelta * mLastPlaybackState.getPlaybackSpeed();
}
mSeekbar.setProgress((int) currentPosition);
}