先上代码:
public class MyService extends Service {
public MyService() {
}
private long mServiceCreatTime;
@Override
public void onCreate() {
super.onCreate();
mServiceCreatTime = System.currentTimeMillis();
}
@Override
public IBinder onBind(Intent intent) {
return new MyBinder();
}
public class MyBinder extends Binder{
public String getRunningTime(){
return MyService.this.getRunningTime();
}
}
public String getRunningTime(){
long runningTime = System.currentTimeMillis()-mServiceCreatTime;
return String.format("服务已运行: %s",dateFormat(runningTime));
}
public String dateFormat(long timeMillions){
Date date = new Date(timeMillions);
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
return sdf.format(date);
}
}
public class MainActivity extends AppCompatActivity {
private TextView mTvRunningTime;
private MyService.MyBinder mMyBinder;
private Handler mHandler = new Handler();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTvRunningTime = (TextView) findViewById(R.id.tv_running_time);
//绑定服务
Intent intent = new Intent(this,MyService.class);
MyServiceConnection myServiceConnection = new MyServiceConnection();
bindService(intent,myServiceConnection, Context.BIND_AUTO_CREATE);
refreshRunningTime();
}
private void refreshRunningTime(){
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
mHandler.post(new Runnable() {
@Override
public void run() {
//通过MyBinder调用MyService中的getRunningTime()方法
if (mMyBinder!=null) {
mTvRunningTime.setText(mMyBinder.getRunningTime());
}
}
});
}
},0,1000);
}
private class MyServiceConnection implements ServiceConnection{
@Override
public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
mMyBinder = (MyService.MyBinder) iBinder;
}
@Override
public void onServiceDisconnected(ComponentName componentName) {
}
}
}
实现步骤:
1.在Service中创建一个Binder的子类MyBinder, 在MyBinder中调用MyService需要提供给外部调用的getRuuningTime()方法;
2.在MyService的onBind()方法中返回MyBinder的实例;
3.在Activity中创建一个ServiceConnection的实现类MyServiceConnection;
4.通过bindService()启动MyService;
5.在MyServiceConnection的onServiceConnected()方法中将iBinder强转为MyBinder, 这样就可以通过MyBinder调用MyService中的getRunningTime()方法了。