2013-08-05 52 views
0

我實現簡單的媒體播放器,但我想通過使用處理程序來處理我的播放器。例如 - 我的OnClick:來自處理程序的Android句柄消息

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; 

和處理此消息。但在這個實現中,我沒有看到我的消息。

您能否提供一些幫助? Thx

回答

0

我會使用Messenger來發送消息並創建一個公共接口來處理回調。無論你要處理這一點,你會怎麼做

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 
    } 
} 

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

然後聲明使者