Android从Service类更新MediaPlayer SeekBar位置

时间:2015-03-02 07:39:16

标签: android android-service android-mediaplayer android-broadcast android-service-binding

我创建了一个流媒体MediaPlayer,它运行在一个单独的服务而不是MainActivity上。用于在用户寻求进度时更新SeekBar位置 我使用广播接收器告诉服务用户寻求的位置。之后服务获取寻找位置和 在MainActivity中更新SeekBar的当前位置。

一切正常,但当用户快速移动SeekBar服务类时 冻结了MainActivity的用户界面和一些时间崩溃。从Service类更新MainActivity的SeekBar的最佳方法是什么?

代码示例。,

MainActivity,

 // Set up constant ID for broadcast of seekbar position
        public static final String BROADCAST_SEEKBAR = "com.gm.sendseekbar";
        private Intent intent;

         @Override
            public void onProgressChanged(SeekBar sb, int progress, boolean fromUser) {
                // TODO Auto-generated method stub
                if (fromUser) {
                    int seekPos = sb.getProgress();
                    intent.putExtra("seekpos", seekPos);
                    sendBroadcast(intent);
                }
            }

服务类

@Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        mp = new MediaPlayer();
        mp.setOnBufferingUpdateListener(this);
        mp.setOnCompletionListener(this);
        mp.setOnInfoListener(this);
        mp.setOnPreparedListener(this);
        mp.setOnSeekCompleteListener(this);
        mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
        audioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
        }

@Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        // Set up receiver for seekbar change
        registerReceiver(broadcastReceiver, new IntentFilter(
                ActivityMain.BROADCAST_SEEKBAR));

}

// Receive seekbar position if it has been changed by the user in the main activity
    private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            sendBufferStartBroadcast();
            updateSeekPos(intent);
        }
    };

    // Update seek position from Activity
    public void updateSeekPos(Intent intent) {

        int seekPos = intent.getIntExtra("seekpos", 0);
        if (mp.isPlaying()) {

            int playPositionInMillisecconds = (mediaFileLengthInMilliseconds / 100)
                    * seekPos;
            mp.seekTo(playPositionInMillisecconds);

        }

    }

1 个答案:

答案 0 :(得分:0)

使用广播可能不是最好的方法,因为您不想告诉每个应用程序应用程序的搜索栏已移动。为什么不使用服务和活动通信?示例:http://blog.philippheckel.com/2012/06/10/android-example-communication-between-activity-and-service-using-messaging/