Service做为Android四大组件之一,才疏学浅的我在近期对它有了点粗鄙的认识,真诚的我就迫不及待地想让大家了解俺对Service的理解,有错误的地方还请大家多多指教。。。
Service它是一种长生命周期的,没有可视化界面,运行于后台的一种服务程序。平时我们手机上很多应用都在后台执行。这也是service重要的原因,除此之外,它也是用来执行需要执行长时间的任务。因为我们知道android是单线程,如果在主线程中跑较长时间任务的话会堵塞主线程。所以我们有时候还需要主线程和Activity之间的通信。
基本的Service用法我就不详细介绍了,先看图解:
下面我们通过在service端实现比较两个数大小的功能,在主线程显示更大的数。
MyBinderService
package com.example.lab4exam03;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
public class MyBinderService extends Service{
int num1;
int num2;
public MyBinderService(){
}
//先创建Service,且只会执行一次
@Override
public void onCreate() {
super.onCreate();
}
//销毁Service
@Override
public void onDestroy() {
super.onDestroy();
}
//执行Service,会执行很多次
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return super.onStartCommand(intent, flags, startId);
}
//接触绑定,因为我们除了通过StartService可以开启Service还可以通过绑定自动创建
@Override
public boolean onUnbind(Intent intent) {
return super.onUnbind(intent);
}
//必须实现的方法,也是最重要的的方法
@Override
public IBinder onBind(Intent intent) {//IBinder是一个接口,而Binder实现了这个接口
return new MyBinder();
}
public class MyBinder extends Binder{
public int IntCompare(){//比较,返回较大值
return (num1 >= num2 ? num1 : num2);
}
public void setData(int num1, int num2){//将Activity里的数据通过IBinder传到Service
MyBinderService.this.num1 = num1;
MyBinderService.this.num2 = num2;
}
}
}
采用AsynvTask的MainActivity
package com.example.lab4exam03;
import com.example.lab4exam03.MyBinderService.MyBinder;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
TextView tv;
Button bt;
Intent intent;
Handler handler;
EditText ed1;
EditText ed2;
MyBinder binder;
int num1,num2;
//为绑定服务的参数
ServiceConnection conn = new ServiceConnection(){
//最精华的部分,就是把安插在Service里的间谍iBinder找过来获取或者传递数据
@Override
public void onServiceConnected(ComponentName arg0, IBinder iBinder) {
binder = (MyBinder) iBinder;
}