... 아직도 못하고 계시나보네요.
딱해보여서 핵심 sample code를 적습니다.
Service class 부분입니다.
public class TestService extends Service {
private Messenger mRemote;
@Override
public IBinder onBind(Intent intent) {
return new Messenger(new RemoteHandler()).getBinder();
}
// Send message to activity
public void remoteSendMessage(String data) {
if (mRemote != null) {
Message msg = new Message();
msg.what = 1;
msg.obj = data;
try {
mRemote.send(msg);
} catch (RemoteException e) {
e.printStackTrace();
}
}
}
// Service handler
private class RemoteHandler extends Handler {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case 0 :
// Register activity hander
mRemote = (Messenger) msg.obj;
break;
default :
remoteSendMessage("TEST");
break;
}
}
}
}
Acitivity 부분 입니다.
public class MainActivity extends Activity {
private Messenger mRemote;
private ServiceConnection mConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
// service 하고 연결될때
mRemote = new Messenger(service);
// Activity handler를 service에 전달하기
if (mRemote != null) {
Message msg = new Message();
msg.what = 0;
msg.obj = new Messenger(new RemoteHandler());
try {
mRemote.send(msg);
} catch (RemoteException e) {
e.printStackTrace();
}
}
}
@Override
public void onServiceDisconnected(ComponentName name) {
// service 하고 연결이 끊길때
mRemote = null;
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// service 연결 시도
Intent serviceIntent = new Intent(this, TestService.class);
bindService(serviceIntent, mConnection, Context.BIND_AUTO_CREATE);
}
@Override
protected void onDestroy() {
super.onDestroy();
// service 연결 해제
unbindService(mConnection);
}
// Test 용 메세지 보내기
public void testSendMessage() {
if (mRemote != null) {
Message msg = new Message();
msg.what = 1;
try {
mRemote.send(msg);
} catch (RemoteException e) {
e.printStackTrace();
}
}
}
// Activity handler
private class RemoteHandler extends Handler {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
}
}
}
unbind 하면 service는 그즉시 동작이 멈춥니다.