Created
September 20, 2017 13:00
-
-
Save thinkerzhangyan/b6128a508e4fa2967652bee2d35e1b8b to your computer and use it in GitHub Desktop.
MessengerActivity
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class MessengerActivity extends Activity { | |
private static final String TAG = "MessengerActivity"; | |
private Messenger mService; | |
private Messenger mGetReplyMessenger = new Messenger(new MessengerHandler()); | |
private static class MessengerHandler extends Handler { | |
@Override | |
public void handleMessage(Message msg) { | |
switch (msg.what) { | |
case MyConstants.MSG_FROM_SERVICE: | |
Log.i(TAG, "receive msg from Service:" + msg.getData().getString("reply")); | |
break; | |
default: | |
super.handleMessage(msg); | |
} | |
} | |
} | |
private ServiceConnection mConnection = new ServiceConnection() { | |
public void onServiceConnected(ComponentName className, IBinder service) { | |
mService = new Messenger(service); | |
Log.d(TAG, "bind service"); | |
Message msg = Message.obtain(null, MyConstants.MSG_FROM_CLIENT); | |
Bundle data = new Bundle(); | |
data.putString("msg", "hello, this is client."); | |
msg.setData(data); | |
msg.replyTo = mGetReplyMessenger; | |
try { | |
mService.send(msg); | |
} catch (RemoteException e) { | |
e.printStackTrace(); | |
} | |
} | |
public void onServiceDisconnected(ComponentName className) { | |
} | |
}; | |
@Override | |
protected void onCreate(Bundle savedInstanceState) { | |
super.onCreate(savedInstanceState); | |
setContentView(R.layout.activity_messenger); | |
Intent intent = new Intent("com.ryg.MessengerService.launch"); | |
bindService(intent, mConnection, Context.BIND_AUTO_CREATE); | |
} | |
@Override | |
protected void onDestroy() { | |
unbindService(mConnection); | |
super.onDestroy(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment