从业务数据发送到活动的Android(Send Data from Service To Activ

2019-07-18 06:13发布

我建立一个使用服务播放的音乐播放器。 我有一个控制(播放,暂停,下一首,...)服务的活动UI。 我想按下一个或下一个按钮时,从我的服务更新UI。 我想传递一个整数值。 这里是我的代码:

我已经用于通信的使者。 在我服务的代码如下所示:

enum Event {
    NextSongChanged, CurrentPlayingSong
};

public synchronized void registerHandler(Messenger m) {
    clients.add(m);
}


private void emit(Event e) {
    for (Messenger m : clients) {
        try {
            m.send(Message.obtain(null, e.ordinal()));
        } catch (RemoteException exception) {
            /* The client must've died */
            clients.remove(m);
        }
    }
}

我的方法,我在旁边按一下按钮调用:

public synchronized void playnext() {
    reset();
    if(songIndex <  (songsList.size() - 1)) {
        songIndex += 1;
        playSong(songIndex);
    } else {
        songIndex = 0;
        playSong(songIndex);
    }
    emit(Event.NextSongChanged);
}

当我火NextSongChanged事件我想给“songIndex”变量传递到我的活动。 就如何实现这一目标的任何想法?

我的动态代码来处理事件:

private Messenger playerMessenger = new Messenger(new Handler() {
    @Override
    public void handleMessage(Message msg) {
        switch (MyService.Event.values()[msg.what]) {
            case NextSongChanged:
                //String songTitle = songsList.get(currentSongIndex+1).get("songTitle");
                //currentSongIndex += 1;
                //songTitleLabel.setText(songTitle);
                //updatePlaying();
                break;

            case CurrentPlayingSong:
                break;
        }
    }
});

Answer 1:

示例代码,希望可以帮助别人

1.设置处理程序(接收消息)和Messenger(通信) MainActivity.java

Messenger msgService;
boolean isBound;

ServiceConnection connection = new ServiceConnection() {

    @Override
    public void onServiceDisconnected(ComponentName name) { isBound = false; }

    @Override
    public void onServiceConnected(ComponentName name, IBinder service) {
        isBound = true;
        msgService = new Messenger(service);
    }
};

public void sendMessage(View view) {
    if (isBound) {
        try {
            Message message = Message.obtain(null, MessangerService.MESSAGE, 1, 1);
            message.replyTo = replyMessenger;

            Bundle bundle = new Bundle();
            bundle.putString("rec", "Hi, you hear me");
            message.setData(bundle);

            msgService.send(message); //sending message to service

        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }
}
//setting reply messenger and handler
Messenger replyMessenger = new Messenger(new HandlerReplyMsg());

class HandlerReplyMsg extends Handler {
    @Override
    public void handleMessage(Message msg) {
        super.handleMessage(msg);
        String recdMessage = msg.obj.toString(); //msg received from service
        toast(recdMessage);
    }
}

2.设置服务类MessengerService.java

Messenger replyMessanger;
final static int MESSAGE = 1;

class IncomingHandler extends Handler {

    @Override
    public void handleMessage(Message msg) {

        if (msg.what == MESSAGE) {
            Bundle bundle = msg.getData();
            toast(bundle.getString("rec"));//message received
            replyMessanger = msg.replyTo; //init reply messenger
            doSomething();
        }
    }
}

private void doSomething() {
    // do stuff

    if (replyMessanger != null)
        try {
            Message message = new Message();
            message.obj = "Yes loud and clear";
            replyMessanger.send(message);//replying / sending msg to activity
        } catch (RemoteException e) {
            e.printStackTrace();
        }
}
Messenger messenger = new Messenger(new IncomingHandler());

@Override
public IBinder onBind(Intent intent) {
    return messenger.getBinder();
}

请务必在申报服务manifestbinding/unbinding的活动服务。



文章来源: Send Data from Service To Activity Android