public void say(){
Toast.makeText(this, "xiaoer", Toast.LENGTH_SHORT).show();
System.out.println(this.toString());
System.out.println("haha");
}
package com.example.server;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.widget.Toast;
public class MyServer extends Service {
public class myBind extends Binder {
public void says(String name) {
say();
}
}
@Override
public IBinder onBind(Intent intent) {
System.out.println("onBind");
return new myBind();
}
@Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
System.out.println("onCreate");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
System.out.println("onStartCommand");
return super.onStartCommand(intent, flags, startId);
}
public void say(){
Toast.makeText(this, "xiaoer", Toast.LENGTH_SHORT).show();
System.out.println(this.toString());
System.out.println("haha");
}
@Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
System.out.println("OnDestroy");
}
}
//可以通过绑定服务的方式调用方法
绑定服务的时候会传入一个ServerConnection的接口实现类
自己定义一个类在
//可以通过绑定服务的方式调用方法
绑定服务的时候会传入一个ServerConnection的接口实现类
自己定义一个类在
中会返回server中 onBind方法返回的接口IBinder的实现类myBind
我们可以在myBind这个内部类中调用server的方法
public class MainActivity extends Activity {
myBind bind ;
private MyServiceConnection connection;
public class MyServiceConnection implements ServiceConnection {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
// TODO Auto-generated method stub
bind = (myBind) service;
}
@Override
public void onServiceDisconnected(ComponentName name) {
// TODO Auto-generated method stub
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
connection = new MyServiceConnection();
}
public void start(View v) {
Intent it = new Intent();
it.setClass(this, MyServer.class);
bindService(it, connection, BIND_AUTO_CREATE);
}
public void stop(View v) {
Intent it = new Intent();
it.setClass(this, MyServer.class);
unbindService(connection);
}
public void say(View v) {
bind.says("haha");
}
}