android-如何将数据从服务发送到片段“每秒”?

时间:2018-08-29 19:02:30

标签: android service broadcastreceiver fragment broadcast

我有一个媒体播放器服务,我需要片段UI进行更新或与服务数据同步。 目前,我正在使用广播发送和接收数据。但是我的问题是,在Android中有更好的方法吗?

服务中:

private void startBroadcast() {
    if(broadcastThread!= null && !broadcastThread.isInterrupted())
        broadcastThread.interrupt();
    broadcastThread = new Thread(){
        @Override
        public void run() {
            try {
                while(!isInterrupted()) {
                    Intent intent = new Intent(FILTER);
                    intent.putextra("foo",1);
                    sendBroadcast(intent);
                    sleep(1000);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    };
    broadcastThread.start();
}

在片段中:

private BroadcastReceiver serviceReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        int foo= intent.getIntExtra("foo", 0);
        // bla bla
    }
};
.
.
@Override
public void onResume() {
    super.onResume();
    Objects.requireNonNull(getActivity()).registerReceiver(serviceReceiver ,FILTER);
}

2 个答案:

答案 0 :(得分:0)

您可以使用绑定服务将服务连接到您的活动 然后用这个更新所有片段

bindService(oIntent, mServiceConnection, Context.BIND_AUTO_CREATE);

private ServiceConnection mServiceConnection = 
    new ServiceConnection(){
        public void onServiceConnected(
            ComponentName cName, IBinder service){
                MyBinder binder = (MyService.MyBinder) service;
                mService = binder.getService(); 
                // Get a reference to the Bound Service object.
                mServiceBound = true;
    }
    public void onServiceDisconnected(ComponentName cName){
        mServiceBound= false;
    }
};

在您要更改活动后,应该取消连接

if (mServiceBound){
        unbindService(mServiceConnection);
        mServiceBound = false;
}

答案 1 :(得分:0)

我在MediaPlayer中也遇到了类似的问题,我也必须每秒钟更新一次UI组件。 我使用了Runnable + Handler组合,像这样:

//...
private Handler mHandler;
private Runnable mSeekBarUpdater
//...

@Override
protected void onStart() {
    super.onStart();
 //...
    int result;
      // ...
    if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {

        mMediaPlayer.setOnCompletionListener(this);
        // Start playing and set isPlaying to true. This attribute is required on rotating screen
        mMediaPlayer.start();
        isPlaying = true;
        /**
         * Preparing Handler object and a Runnable in order to
         * update SeekBar status
         */
        if (mHandler == null) {
            mHandler = new Handler();
        }
        if (mSeekBarUpdater == null) {
            mSeekBarUpdater = new Runnable() {
                @Override
                public void run() {                
                    if (mMediaPlayer != null && mHandler != null) {
                        if (mMediaPlayer.isPlaying()) {
                            // Refreshing SeekBar position
                            mCurrentPosition = mMediaPlayer.getCurrentPosition();                              
                            mSeekBar.setProgress(mCurrentPosition);
// .. put your code here in order to refresh your UI components
                        }
                        // Refreshing on every second
                        mHandler.postDelayed(this, 1000);
                    }
                }
            };
        }
        PlayerActivity.this.runOnUiThread(mSeekBarUpdater);
    }
}