• Android四大组件之Service(一)


    Service是Android四大组件之一,它可以在后台执行长时间运行操作而没有用户界面的应用组件。

    Service的启动方式有两种:startService启动和bindService启动,今天先讲讲startService。

    先讲讲启动模式:分为显示启动及隐式启动

    显式启动

    1. Intent intentStart = new Intent(ServiceActivity.this, StartService.class);
    2. startService(intentStart);

    隐式启动:需要设置一个Action,可以把Action设置成Service的全路径名字,在这种情况下android:exported默认为true

    1. Intent serviceIntent=new Intent();
    2. serviceIntent.setAction("com.android.StartService");
    3. startService(serviceIntent);

     两种启动方法都可以在同一个应用中使用,对于不同的应用,只能使用隐式方法。

    本篇文章主要讲显示启动,而且是使用startService的方式。如上面显式启动一样,使用Intent来启动service,通过该方式启动的Service,调用者与Service之间没有关联,即使调用者退出了,Serviec仍然运行,必须显式调用stopService来停止,并且需要将启动Service的Intent传递给stopService()方法。

    stopService(intent);

    在使用结果没有手动调用 stopService,就会造成内存泄漏,因此要记得关闭Service。

    下面看看通过startService启动的生命周期。

    onCreate():当Service第一次被创建时,由系统调用。

    onStart():当调用startService方法启动Service时,该方法被调用。

    onDestory():当调用stopService或者被系统回收时,该方法被调用。

    onCreate跟onDestory只能被调用一次,onStart可以被调用多次。比如第一次调用startService时,这时Service还没有被创建,会调用onCreate方法,然后再调用onStart方法;此时在其他调用再一次用startService启动Service时,只会调用onStart方法,而不会调用onCreate已经存在了,也就是说Service只能有一个,不能创建出两个一摸一样的来,onDestory也是同样的道理,Service已经被销毁了,onDestory就不会再被调用了。

    下面是例子:

    创建MyService.java,继承Service

    1. public class MyService extends Service {
    2. @Override
    3. public void onCreate() {
    4. super.onCreate();
    5. MLog.e(getClass().getName(), "onCreate");
    6. }
    7. @Override
    8. public int onStartCommand(Intent intent, int flags, int startId) {
    9. MLog.e(getClass().getName(), "onStartCommand");
    10. return super.onStartCommand(intent, flags, startId);
    11. }
    12. @Override
    13. public void onDestroy() {
    14. MLog.e(getClass().getName(), "onDestroy");
    15. super.onDestroy();
    16. }
    17. @Nullable
    18. @Override
    19. public IBinder onBind(Intent intent) {
    20. return null;
    21. }
    22. }

    AndroidManifest.xml中声明该Service

    ".service.MyService"/>

    Activity或Fragment中去启动该Service,或者去关闭该Service,两个按钮,一个启动,一个关闭。

    1. Intent intentStart = new Intent(ServiceActivity.this, StartService.class);
    2. findViewById(R.id.btn_start).setOnClickListener(new View.OnClickListener() {
    3. @Override
    4. public void onClick(View v) {
    5. startService(intentStart);
    6. }
    7. });
    8. findViewById(R.id.btn_stop).setOnClickListener(new View.OnClickListener() {
    9. @Override
    10. public void onClick(View v) {
    11. stopService(intentStart);
    12. }
    13. });

  • 相关阅读:
    静态&动态&文件通讯录
    设置Mac上Git的多账户配置,用于同时访问GitLab和Gitee
    达摩院中试比高:欢迎参加2024阿里巴巴全球数学竞赛(AI可参赛)
    springboot 数据字典设计思路:字典表+字典枚举 两者兼故方案,查询返回结果在controller方法上添加注解进行字典翻译
    Redis 数据结构
    毕业设计-机器视觉的疲劳驾驶检测系统-python-opencv
    找出重复成员
    11.11练习题
    TensorFlow入门(五、指定GPU运算)
    业务流程管理BPM到底有什么用
  • 原文地址:https://blog.csdn.net/taoyuxin1314/article/details/126268026