Android四大组件之Service(一)

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

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

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

显式启动

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

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

Intent serviceIntent=new Intent(); 
serviceIntent.setAction("com.android.StartService");
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

public class MyService extends Service {
    @Override
    public void onCreate() {
        super.onCreate();
        MLog.e(getClass().getName(), "onCreate");
    }
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        MLog.e(getClass().getName(), "onStartCommand");
        return super.onStartCommand(intent, flags, startId);
    }
    @Override
    public void onDestroy() {
        MLog.e(getClass().getName(), "onDestroy");
        super.onDestroy();
    }

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

AndroidManifest.xml中声明该Service

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

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

Intent intentStart = new Intent(ServiceActivity.this, StartService.class);
        findViewById(R.id.btn_start).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startService(intentStart);
            }
        });
        findViewById(R.id.btn_stop).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                stopService(intentStart);
            }
        });

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值