将数据从服务发送到Android活动

时间:2013-01-16 05:01:07

标签: android android-activity android-service

我正在构建一个使用服务进行播放的音乐播放器。我有一个Activity 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;
        }
    }
});

1 个答案:

答案 0 :(得分:15)

示例代码希望可以帮助其他人

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服务活动中声明了服务。