第十四单元:Service生命周期和启动方式

Service生命周期和启动方式

  • Service介绍
  • Service特点
  • 如何创建Service
  • Service的启动方式以及生命周期
    启动方式一 (startService)
    启动方式二 (bindService)

Service介绍

1.Service,服务,是四大组件之一, 和Activity 非常相似, 一般运行在后台, 没有用户界面, 可执行的程序
2.Activity 和 Service的区别
(1)不同点:
Activity : 可以和用户交互, 页面可见
Service : 后台运行, 没有界面
(2)相同点:
在清单文件中注册, 都有自己的生命周期

Service特点

service在后台运行,不用与用户进行交互。即使应用退出,服务也不会停止。
当应用进程被杀死时,服务便会停止.
service运行在主线程中,当需要执行耗时操作的时候,需要在服务中创建子线程完成
service 的用途:播放音乐;后台下载大文件等

如何创建Service

1, 定义一个类, 继承Service
2, 重写父类的方法, onBind() — 必须重写的方法
3, 在清单文件中, 注册Service

Service的启动方式以及生命周期

启动方式一 (startService)

1,右键创建一个Service

public class MyService extends Service {
    private static final String TAG = "嘿嘿嘿";

    public MyService() {
        Log.i(TAG, "MyService: hellow");
                
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }
}

布局文件
两个按钮,一个启动,一个停止

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    android:orientation="vertical">
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/button1"
        android:text="启动一个服务" />
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/button2"
        android:text="停止一个服务" />
</LinearLayout>

java 代码文件

public class MainActivity extends AppCompatActivity {
    private Button button1;
    private Button button2;
    private Intent intent;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        button1 = (Button) findViewById(R.id.button1);
        button2 = (Button) findViewById(R.id.button2);
        button1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                stopService(intent);
            }
        });
        button2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                intent = new Intent(MainActivity.this, MyService.class);
                startService(intent);
            }
        });

    }
}

完善方法,验证生命周期 如果服务已经开启,就不会重复的执行 onCreate() ,而是调用 onStart() 或
onStartCommand()。而服务停止的时候调用 onDestory()

一旦服务开启跟开启者就没有任何关系; 开启者退出之后,服务还是可以在后台长期运行的。前提是没有调用 stopService(Intent);
开启者不能调用服务里面的方法

启动方式:onCreate() — onStartCommand() — onDestroy()
开启服务:startService()
停止服务:stopService()

启动方式二 (bindService)

使用Service的步骤如下:

1,定义一个类,并继承 Service
2,在 AndroidManifest.xml 中配置此 Service
3,使用 Context 的 bindService(Intent, ServiceConnection, int) 方法来启动此 Service
4,不使用该服务时,调用 unbindService(ServiceConnection) 方法停止此 Service

绑定服务不会调用 onStart() 或 onStartCommand() 方法。 注意:同一个服务, 只能被同一个启动源, 绑定一次,
除非解绑后, 可以再次绑定

特点:
bind的方式开启服务,绑定服务,调用者挂了,服务也会跟着挂掉。
绑定者可以调用服务里面的方法。

bindService代码
(1)创建服务:自定义类继承Service,返回代理人,方便开启者调用服务中的方法

public class MyService extends Service {
    private static final String TAG = "嘿嘿嘿";

    public MyService() {
        Log.i(TAG, "MyService: hellow");

    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        return new MyBinder();
    }
    class MyBinder extends Binder {
        public MyService getService(){
            return MyService.this;
        }
    }
    public void send(){
        Toast.makeText(this, "发送了", Toast.LENGTH_SHORT).show();
    }
    //服务中提供的方法
    public void take(){
        Toast.makeText(this, "收到了", Toast.LENGTH_SHORT).show();
    }
}

(2)清单文件注册服务:

<service android:name=".MyService"></service>

(3)绑定服务和解除绑定

public class MainActivity extends AppCompatActivity {
    private Intent intent;
    private MyService myService;
    private ServiceConnection connection=new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            myService= ((MyService.MyBinder)service).getService();
        }
        @Override
        public void onServiceDisconnected(ComponentName name) {
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //1.绑定服务
        intent =new Intent(this,MyService.class);
        bindService(intent,connection, Service.BIND_AUTO_CREATE);
    }
    protected void onDestroy() {
        super.onDestroy();
        unbindService(connection);
    }
    public void send(View view){
        myService.send();
    }
}

总结:
绑定方式:onCreate() – onBind() — onUnbind() — onDestroy()
绑定服务:bindService()
解除绑定:unbindService()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值