TestService类:
package com.itheima74.whybindservice.service;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.support.annotation.Nullable;
/**
* 0.定义一个服务,需要在清单文件注册
* Created by My on 2017/2/23.
*/
public class TestService extends Service {
@Nullable
@Override
public IBinder onBind(Intent intent) {
System.out.println("onBind");
// 3.将中间人对象返回
return new MyBinder();
}
@Override
public void onCreate() {
System.out.println("onCreate");
super.onCreate();
}
@Override
public void onDestroy() {
System.out.println("onDestroy");
super.onDestroy();
}
/**
* 1.定义服务中的TestMethod方法
*/
public void testMethod() {
System.out.println("我是服务中的TestMethod方法");
}
/**
* 2.定义中间人对象(IBinder类的实例),它能间接调用服务中的方法
*/
public class MyBinder extends Binder {
public void callTestMethod() {
TestService.this.testMethod();
}
}
}
MainActivity类:
package com.itheima74.whybindservice;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import com.itheima74.whybindservice.service.TestService;
/**
* 为什要BindService?
* 为了调用服务中的方法
*/
public class MainActivity extends AppCompatActivity {
private MyConn mMConn;
private TestService.MyBinder mBinder;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 4.连接到服务
Intent intent = new Intent(this, TestService.class);
mMConn = new MyConn();
bindService(intent, mMConn, BIND_AUTO_CREATE);
}
// 6.点击按钮,调用服务中的方法
public void click(View view) {
mBinder.callTestMethod();
}
private class MyConn implements ServiceConnection {
// 服务连接成功调用
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
// 5.获取中间人对象
mBinder = (TestService.MyBinder) service;
}
// 服务失去连接调用
@Override
public void onServiceDisconnected(ComponentName name) {
}
}
@Override
protected void onDestroy() {
super.onDestroy();
// 7.Activity销毁时取消绑定服务,否则会报红色日志;
unbindService(mMConn);
}
}
运行结果:
02-23 07:38:56.337 2522-2522/com.itheima74.whybindservice I/System.out: onCreate
02-23 07:38:56.338 2522-2522/com.itheima74.whybindservice I/System.out: onBind
02-23 07:38:59.358 2522-2522/com.itheima74.whybindservice I/System.out: 我是服务中的TestMethod方法
02-23 07:39:00.531 2522-2522/com.itheima74.whybindservice I/System.out: 我是服务中的TestMethod方法
02-23 07:39:01.148 2522-2522/com.itheima74.whybindservice I/System.out: 我是服务中的TestMethod方法