Android 四大组件(二)Service详解

  • 作用:提供 需在后台长期运行的服务,

  • 特点:无用户界面、在后台运行、生命周期长

Android 四大组件(二)Service详解_第1张图片

1.Service有两种启动方式:Context.startService() 

在Activity 中  
startService(new Intent(this,StartTypeService.class));

intent里面可以携带数据传递给service

开始服务

在Activity onDestory 的时候,服务也不销毁。

需要在Activity OnDestory 手动调用销毁:

serviceIntent=new Intent(this,StartTypeService.class);
    @Override
    protected void onDestroy() {
        stopService(serviceIntent);
        super.onDestroy();
    }

2. Context.bindService()

在Actiivity中 使用:

        int flag= Context.BIND_AUTO_CREATE;
        Intent intent=new Intent(this, BindTypeService.class);
        ServiceConnection conn=new ServiceConnection() {
            @Override
            public void onServiceConnected(ComponentName name, IBinder service) {

            }

            @Override
            public void onServiceDisconnected(ComponentName name) {

            }
        };
        bindService(intent,conn,flag);

 绑定

Activity  返回 销毁掉

Binder 可以用来从service 返回值给Activity,从而实现交互

    public class LocalBinder extends android.os.Binder {
         public String getData(){
             return "test";
         }
    }
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        LocalBinder localBinder=new LocalBinder();
        super.onBind(intent);
//        localBinder.get
        return localBinder;
    }

官方文档提现我们需要注意的是:run in the main thread of their hosting process. This means that, if your service is going to do any CPU intensive (such as MP3 playback) or blocking (such as networking) operations, it should spawn its own thread in which to do that work

翻译过来就是如果需要在服务里面做复杂耗时操作就要另起线程来做。有个IntentService的,Android封装好的用来处理耗时的

public class MyIntentService extends IntentService {
    private static final String TAG ="MyIntentService" ;

    /**
     * Creates an IntentService.  Invoked by your subclass's constructor.
     *
     * @param name Used to name the worker thread, important only for debugging.
     */
    public MyIntentService(String name) {
        super(name);
    }
    public MyIntentService() {
        super(null);
    }
    /**
     * Creates an IntentService.  Invoked by your subclass's constructor.
     *
     * @param name Used to name the worker thread, important only for debugging.
     */


    @Override
    public void onStart(@Nullable Intent intent, int startId) {
        Log.i(TAG, "onStart: ");
        super.onStart(intent, startId);
    }

    //直接在这个方法里面做耗时操作
    @Override
    protected void onHandleIntent(@Nullable Intent intent) {

        for (int i=0;i<100;i++){
            Log.i(TAG, "onHandleIntent: "+i);
        }
    }


}

注意需要一个空的构造方法,原因还没弄懂

提出两个问题:

1.onconnected  和 onbind  谁先调用 

我实测是onbind先

2.为什么service要必须重写onbind方法,bind只是启动的一种方式?

 

service接口   onbind方法是抽象的,实测在使用startservice 启动的时候,的确没调用onbind

你可能感兴趣的:(Android,基础知识整理,android,java,开发语言)