package
com.example.studentclient;
import
com.example.studentservice.IStudentService;
import
android.os.Bundle;
import
android.os.IBinder;
import
android.os.RemoteException;
import
android.app.Activity;
import
android.app.AlertDialog;
import
android.content.ComponentName;
import
android.content.Context;
import
android.content.Intent;
import
android.content.ServiceConnection;
import
android.view.Menu;
import
android.view.View;
import
android.view.View.OnClickListener;
import
android.widget.Button;
public
class
MainActivity
extends
Activity {
private
Button btn1, btn2;
private
IStudentService stuService =
null
;
private
ServiceConnection serviceConnection =
new
ServiceConnection() {
@Override
public
void
onServiceDisconnected(ComponentName name) {
}
@Override
public
void
onServiceConnected(ComponentName name, IBinder service) {
stuService = IStudentService.Stub.asInterface(service);
}
};
@Override
protected
void
onCreate(Bundle savedInstanceState) {
super
.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn1 = (Button)findViewById(R.id.button1);
btn2 = (Button)findViewById(R.id.button2);
btn1.setOnClickListener(
new
OnClickListener() {
@Override
public
void
onClick(View v) {
bindService(
new
Intent(
"com.example.studentservice.IStudentService"
),
serviceConnection, Context.BIND_AUTO_CREATE);
}
});
btn2.setOnClickListener(
new
OnClickListener() {
@Override
public
void
onClick(View v) {
StringBuilder sb =
new
StringBuilder();
try
{
if
(stuService ==
null
) {
new
AlertDialog.Builder(MainActivity.
this
).setTitle(
"Error"
)
.setMessage(
"stuService is null"
).setPositiveButton(
android.R.string.ok,
null
).show();
return
;
}
sb.append(
"学生名称为:"
+ stuService.getStudent().getName() +
"\n"
);
sb.append(
"年龄为:"
+ stuService.getStudent().getAge() +
"\n"
);
sb.append(
"map 对象内容为如下:"
+ stuService.getMap(
"中国"
, stuService.getStudent())
.toString());
}
catch
(RemoteException e) {
e.printStackTrace();
}
new
AlertDialog.Builder(MainActivity.
this
).setTitle(
"调用外部服务"
)
.setMessage(sb.toString()).setPositiveButton(
android.R.string.ok,
null
).show();
}
});
}
}