五、绑定Service,定义一个类MyConn实现ServiceConnection接口,实现其中的方法
public void onServiceConnected(ComponentName name, IBinder service),其中的service就是该Activity和Service的代理人,可以通过该对象的引用间接地调用Service内的方法。
package cn.zengfansheng.callMethodInService;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.view.View;
public class MainActivity extends Activity {
private ServiceConnection conn;
private IService iService;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
/**
* 绑定服务
* @param view
*/
public void bind(View view) {
Intent service = new Intent(this, MyService.class);
conn = new MyConn();
this.bindService(service, conn, Context.BIND_AUTO_CREATE);
}
private class MyConn implements ServiceConnection {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
System.out.println("绑定成功了。。。");
iService = (IService) service;
}
@Override
public void onServiceDisconnected(ComponentName name) {
}
}
/**
* 调用服务内的方法
*
* @param view
*/
public void call(View view) {
iService.callMethodInService();// 间接地调用了Service中的方法
}
} |