首先定义一个Service
的子类。
public class MyService extends Service {
public MyService() {
}
@Override
public IBinder onBind(Intent intent) {
//返回MyBind对象
return new MyBinder();
}
private void methodInMyService() {
Toast.makeText(getApplicationContext(), "服务里的方法执行了。。。",
Toast.LENGTH_SHORT).show();
}
/**
* 该类用于在onBind方法执行后返回的对象,
* 该对象对外提供了该服务里的方法
*/
private class MyBinder extends Binder implements IMyBinder {
@Override
public void invokeMethodInMyService() {
methodInMyService();
}
}
}
自定义的MyBinder
接口
public interface IMyBinder {
void invokeMethodInMyService();
}
接着在Manifest.xml文件中配置该Service
<service android:name=".MyService"/>
在Activity中绑定并调用服务里的方法
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="start"
android:text="开启服务"
android:textSize="30sp" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="invoke"
android:text="调用服务的方法"
android:textSize="30sp" />
</LinearLayout>
绑定服务的Activity:
public class MainActivity extends Activity {
private MyConn conn;
private Intent intent;
private IMyBinder myBinder;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
//开启服务按钮的点击事件
public void start(View view) {
intent = new Intent(this, MyService.class);
conn = new MyConn();
//绑定服务,
// 第一个参数是intent对象,表面开启的服务。
// 第二个参数是绑定服务的监听器
// 第三个参数一般为BIND_AUTO_CREATE常量,表示自动创建bind
bindService(intent, conn, BIND_AUTO_CREATE);
}
//调用服务方法按钮的点击事件
public void invoke(View view) {
myBinder.invokeMethodInMyService();
}
private class MyConn implements ServiceConnection {
@Override
public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
//iBinder为服务里面onBind()方法返回的对象,所以可以强转为IMyBinder类型
myBinder = (IMyBinder) iBinder;
}
@Override
public void onServiceDisconnected(ComponentName componentName) {
}
}
}
绑定本地服务调用方法的步骤:
- 在服务的内部创建一个内部类 提供一个方法,可以间接调用服务的方法
- 实现服务的onbind方法,返回的就是这个内部类
- 在activity 绑定服务。bindService();
- 在服务成功绑定的回调方法onServiceConnected, 会传递过来一个 IBinder对象
- 强制类型转化为自定义的接口类型,调用接口里面的方法。