Android中的Service

原创 2017年01月03日 15:35:17

Service

一、特点:

    Android四大组件之一
    没有UI,后台处理耗时操作或者执行长期运行任务
    会影响进程的优先级,从而影响内存进程被杀几率

二、与Thread区别
运行线程,service运行在UI线程,可以再起一个线程。
机制:Service作为远端全局工作,可以和任何Activity交互,Thread引用范围局限在Activity
优先级:Service会影响进程优先级,线程优先级跟进程无关。
生命周期:Service有生命周期方便管理。Thread无。
进程:Service可跨进程运行,Thread无。

三、Activity与Service交互

public class MainActivity extends Activity implements View.OnClickListener {
    private static final String TAG = ">>>MainActivity";

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            Log.d(TAG, "receive message:" + msg.what);
        }
    };

    private ServiceConnection mSerCon = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
//            自定义Binder
//            TestService.MyBinder binder = (TestService.MyBinder) service;
//            service回调
//            binder.setCallback(new TestService.Callback() {
//                @Override
//                public void sendMessageToActivity(int what, int arg1, int arg2, Object object) {
//                    Log.d(TAG, "service sendMessageToActivity:" + what);
//                }
//            });
//            Activity调用Service
//            Log.d(TAG, "onServiceConnected, count:" + binder.count(2, 3));
            //使用Messenger,activity,service相互调用
            Messenger myMessenger = new Messenger(service);
            try {
                myMessenger.send(Message.obtain(mHandler, 1, mHandler));
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            Log.d(TAG, "onServiceDisConnected");
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        findViewById(R.id.startService).setOnClickListener(this);
        findViewById(R.id.stopService).setOnClickListener(this);
        findViewById(R.id.bindService).setOnClickListener(this);
        findViewById(R.id.unbindService).setOnClickListener(this);
        findViewById(R.id.bindService2).setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.startService:
                Intent intent = new Intent(this, TestService.class);
                intent.putExtra(TestService.INTENT_EXTRA.A, 8);
                startService(intent);

                intent.putExtra(TestService.INTENT_EXTRA.A, 9);
                startService(intent);
                break;
            case R.id.stopService:
                stopService(new Intent(this, TestService.class));
                break;
            case R.id.bindService:
                bindService(new Intent(this, TestService.class), mSerCon, BIND_AUTO_CREATE);//表示绑定的时候如果service不存在则自动创建
                break;
            case R.id.unbindService:
                unbindService(mSerCon);
                break;
            case R.id.bindService2:
                startActivity(new Intent(this, AnotherActivity.class));
                break;
        }
    }
}
public class TestService extends Service {
    private static final String TAG = ">>>TestService";

    public static final class INTENT_EXTRA {
        public static String A = "a";
    }

    private Callback mCallback;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            Handler clientHandler = (Handler) msg.obj;
            Log.d(TAG, "receiver message:" + msg.what + "," + msg.obj);
            //service回发消息
            clientHandler.sendEmptyMessage(2);
        }
    };

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        Log.d(TAG, "service onBind");
//        return new MyBinder();自定义binder
        return new Messenger(mHandler).getBinder();//使用Messenger,activity,service相互调用
    }

    @Override
    public boolean onUnbind(Intent intent) {
        boolean ret = super.onUnbind(intent);
        Log.d(TAG, "service onUnbind, return:" + ret);
        return ret;
    }

    @Override
    public void onRebind(Intent intent) {
        Log.d(TAG, "service onRebind");
        super.onRebind(intent);
    }

    @Override
    public void onCreate() {
        Log.d(TAG, "service onCreate, looper:" + Looper.myLooper());
        super.onCreate();

//        mHandler.postDelayed(new Runnable() {
//            @Override
//            public void run() {
//                停止service
//                stopSelf();
//                  根据id暂停service
//                stopSelfResult()
//            }
//        }, 5000);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d(TAG, "service onStartCommand, looper:" + Looper.myLooper() + "," + intent);
        if (intent != null) {
            Log.d(TAG, "service arg:" + intent.getIntExtra(INTENT_EXTRA.A, 0));
        }
        if (mCallback != null) {
            mCallback.sendMessageToActivity(88, 0, 0, null);
        }
        return START_REDELIVER_INTENT;
    }

    @Override
    public void onDestroy() {
        Log.d(TAG, "service onDestory");
        super.onDestroy();
    }

    //Activity调用Binder方法
    class MyBinder extends Binder {
        public int count(int a, int b) {
            return a + b;
        }
        //设置回调方法
        public void setCallback(Callback callback) {
            mCallback = callback;
        }
    }

    interface Callback {
        void sendMessageToActivity(int what, int arg1, int arg2, Object object);
    }
}

四、Service生命周期

这里写图片描述

五、onStartCommand返回值
START_STICKT 如果service被系统杀掉,会稍后被重启,但不会重传intent
START_NOT_STICKY 如果service被系统杀掉则不会被重启
START_REDELIVER_INTENT如果service被系统杀掉,会稍后被重启,且会重传intent

六、IntentService

    //单线程队列化执行,执行完后自动结束
    class IntentTestService extends IntentService{

        public IntentTestService(String name) {
            super(name);

        }

        @Override
        protected void onHandleIntent(Intent intent) {
            //已经在一个线程里面了,可以做任何耗时操作
        }
    }
版权声明:本文为博主原创文章,未经博主允许不得转载。 举报

相关文章推荐

返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

(最多只允许输入30个字)