两个button按钮:
<Button
android:id="@+id/bt_one"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="绑定服务"
/>
<Button
android:id="@+id/bt_two"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="activity向服务发送"
/>
写一个BindService类继承Service:
public class BindService extends Service{
private Messenger messenger;//创建一个信使
@Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
messenger = new Messenger(handler);
}
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return messenger.getBinder();
}
Handler handler = new Handler(){
public void handleMessage(android.os.Message msg) {
super.handleMessage(msg);
String string = (String) msg.obj;
Log.e("",string);
Message message = new Message();
message.obj="收到消息了";
Messenger aMessenger = msg.replyTo;
try {
aMessenger.send(message);
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
};
};
}
Mainactivity:
public class MainActivity extends Activity implements OnClickListener {
private Messenger sMessenger;//service下的信使
private Messenger aMessenger;//activity下的信使
private Button bt_one,bt_two;
private Conn conn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
conn = new Conn();
aMessenger=new Messenger(handler);
}
private void initView() {
bt_one = (Button) findViewById(R.id.bt_one);
bt_two = (Button) findViewById(R.id.bt_two);
bt_one.setOnClickListener(this);
bt_two.setOnClickListener(this);
}
Handler handler = new Handler(){
public void handleMessage(android.os.Message msg) {
super.handleMessage(msg);
String string = (String) msg.obj;
Log.e("",string);
};
};
@Override
public void onClick(View v) {
if (R.id.bt_one==v.getId()) {
//绑定服务的
Intent intent = new Intent(MainActivity.this,BindService.class);
bindService(intent, conn,Context.BIND_AUTO_CREATE);
}else {
//通信用的
Message message = new Message();
message.obj="发送消息了";
message.replyTo=aMessenger;//replayto:带返回消息的属性 相当于将activity下的信使装到消息里面
try {
sMessenger.send(message);//service下的信使将消息带走
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
@Override
protected void onDestroy() {
unbindService(conn);
super.onDestroy();
}
private class Conn implements ServiceConnection{
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
sMessenger=new Messenger(service);//获取service下的信使
}
@Override
public void onServiceDisconnected(ComponentName name) {
}
}
}