Android处理程序处理消息

时间:2013-08-05 01:27:14

标签: android handler

我实现了简单的媒体播放器,但我希望通过使用处理程序来处理我的播放器。例如 - 我的OnClick:

public void playerControls(View v) {
    switch (v.getId()) {
        case R.id.Play:
            if (!PlayerService.isPlay()) {
                Log.i(TAG, DeviceHelper.getMethodName() + " Media start play");
                play.setImageResource(R.drawable.pause);
                service.play();
                trackTitle.setText(service.getTrackTitle());
            } else {
                Log.i(TAG, DeviceHelper.getMethodName() + " Media pause");
                play.setImageResource(R.drawable.play);
                service.pause();
                trackTitle.setText("Paused...");
            }
            break;
        case R.id.NextTrack:
            Log.i(TAG, DeviceHelper.getMethodName() + " Next track please");
            if (PlayerService.isPlay()) {
                service.nextTrack();
                trackTitle.setText(service.getTrackTitle());
            }
            break;
        case R.id.PreviousTrack:
            Log.i(TAG, DeviceHelper.getMethodName() + " Previous track please");
            if (PlayerService.isPlay()) {
                service.previousTrack();
                trackTitle.setText(service.getTrackTitle());
            }
            break;
    }
}

我希望通过处理程序发送消息,如下所示:

case R.id.NextTrack:
        Log.i(TAG, DeviceHelper.getMethodName() + " Next track please");
        if (PlayerService.isPlay()) {
        Message m = new Message;    
        m.what = MyConstant;
        handler.sendMessage(m);
        trackTitle.setText(service.getTrackTitle());
        }
        break;

在另一个类中处理此消息,我实现了我的逻辑。但在这个实现中,我没有看到我的信息。

你能提供一些帮助吗?谢谢

1 个答案:

答案 0 :(得分:0)

我会使用Messenger发送消息并创建一个公共接口来处理回调。

public interface MyCallbacks {
    public void handleMessage(Message m);
}

然后声明信使:

final Messenger mMess = new Messenger(new MyHandler));

class MyHandler extends Handler {
    @Override
    public void handleMessage(Message msg) {
        switch(msg.what) {
            case i: 
            if (mCallback != null)
                mCallback.handleMessage(msg);
        }
    }
}

然后,无论你想在哪里处理,你都会这样做:

public class handlingClient implements MyCallbacks {
    @Override
    public void handleMessage(Message msg) {
        //handles the msg here
    }
}