四大组件之Service

1 两种生命周期
1.1 startService 开启服务

【startService】 -> onCreate()->onStartCommand()->【stopService】 ->
onStop()->onDestroy()

1.2 bindService 绑定服务

【bindService】-> onCreate()->onBind()->【unbindService】->
onUnBind()->onDestroy()

四大组件之Service_第1张图片

2 生命周期方法
外部调用

startService():启动服务
stopService():关闭服务
bindService():启动(配合绑定方法)服务
unbindService():关闭(配合解绑方法)服务

内部自动调用

onCreat():创建服务
onStartCommand():开始服务
onDestroy():销毁服务
onBind():绑定服务
onUnbind():解绑服务

3 实战演练
方式一:

public class MainActivity extends ActionBarActivity {
    int number=38;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void doButton(View v) {
        Intent intent=new Intent();
        switch (v.getId()) {
        case R.id.button1:    
            intent.setAction("com.robin.testservice2.action");
            intent.putExtra("number", number);
            startService(intent);//启动服务
            number++;
            break;

        case R.id.button2:
            intent.setAction("com.robin.testservice2.action");
            stopService(intent);//停止服务
            break;
        default:
            break;
        }
    }        
}

MyService需要在manifests文件中注册

//每两秒cnt自动减1的操作
public class MyService extends Service{
    protected static final String TAG = "robin debug";
    Thread printThread;
    int cnt=-1;
    boolean active=false;
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        Log.e(TAG,"service create");
        super.onCreate();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.e(TAG,"service start command");
        cnt=intent.getIntExtra("number", -1);
        active=true;
        printThread=new Thread(){
            @Override
            public void run() {
                while(active){
                    cnt--;
                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    Log.e(TAG,"progress value--------->"+cnt);
                }
            }
        };
        printThread.start();
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        active=false;
        super.onDestroy();
        Log.e(TAG,"service destroy");
    }
}

以上的操作过程为:在MainActivity界面点击启动关闭服务,在MyService 中会执行

方式二:

public class MainActivity extends ActionBarActivity {
    private ICount count;
    private class MyConn implements ServiceConnection{

        @Override
        public void onServiceConnected(ComponentName name, IBinder binder) {
            count=(ICount) binder;
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            count=null;
        }    
    }
    MyConn conn=new MyConn();
    TextView txt;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Intent service=new Intent("com.robin.testservice3.action");
        //绑定服务
        bindService(service, conn, BIND_AUTO_CREATE);
        txt=(TextView)findViewById(R.id.result);        
    }
    public void doButton(View view ){
        switch (view.getId()) {
        case R.id.button1:
            txt.setText("来自service子线程的计数值:"+count.getCount());
            break;
        case R.id.button2:
            count.setCount(1000);    
            break;
        default:
            break;
        }
    }
    @Override
    protected void onDestroy() {
        //解绑服务
        unbindService(conn);
        super.onDestroy();
    }    
}
public class MyService extends Service{
    protected static final String TAG = "robin debug";
    private boolean active=false;
    private int cnt=0;
    //实现接口ICount
    private class MyBinder extends Binder implements ICount{

        @Override
        public int getCount() {
            return cnt;
        }
        @Override
        public void setCount(int cnt) {
            MyService.this.cnt=cnt;
        }
    }
    MyBinder binder=new MyBinder();

    @Override
    public IBinder onBind(Intent intent) {
        return binder;
    }

    @Override
    public void onCreate() {
        new Thread(new Runnable() {

            @Override
            public void run() {
                active=true;
                while(active){
                    cnt++;
                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    Log.e(TAG,"service thread :cnt----->"+cnt);

                }
            }
        }).start();
        super.onCreate();
    }
    @Override
    public void onDestroy() {
        Log.e(TAG,"service call onDestroy");
        active=false;
        super.onDestroy();
    }
}
public interface ICount { //描述需要的行为(功能)
    public int getCount();
    public void setCount(int cnt);
}

4 特别注意

全局服务使用startService,绑定服务使用bindService
全局、绑定服务需要注册,并且显式调用
startService无法操作service,bindService可以操作
service写成内部类,需要static修饰符(“public static class MyService3 extends Service {}”)

你可能感兴趣的:(Android-难点)