IntentService使用及生命周期

本文深入探讨了IntentService的工作原理,包括其如何在后台异步执行耗时任务,避免主线程阻塞,并通过生命周期方法管理服务的启动与停止。通过实例代码演示了IntentService的创建、生命周期回调及关键方法的使用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

   

  IntentService默认不在主线程中,耗时操作可以在onHandleIntent()做,不会出现线程阻塞的情况。而且省掉了开线程的麻烦。其内部采用了HandleThread实现了异步操作。当onHandleIntent执行完后,会调用stopSelf()停止IntentService。适用于只使用一次的操作


  如果在程序中添加Looper.loop(),生命周期为:无参构造函数 --> onCreate --> onStartCommand --> onHandleIntent.

 当再次启动IntentService只调用 onStartCommand() 和 onHandleIntent()。


  如果没有添加Looper.loop(),每次启动IntentService,生命周期为:

无参构造函数 --> onCreate -->onStartCommand -->onHandleIntent -->onDestory

 

代码:

public class LyrIntentService extends IntentService {

 public LyrIntentService(String name) {
  super(name);
 }

 public LyrIntentService(){
  super("hello");
  Log.i("pull", "无参构造");
 }
 
 @Override
 public void onCreate() {
  super.onCreate();
  Log.i("pull", "onCreate");
 }
 
 @Override
 public int onStartCommand(Intent intent, int flags, int startId) {
  Log.i("pull", "onStartCommand");
  return super.onStartCommand(intent, flags, startId);
 }
 
 @Override
 protected void onHandleIntent(Intent intent) {
  Log.i("pull", "onHandleIntent");

  //
  Toast.makeText(getApplicationContext(), "onHandleIntent", 1).show();
  Looper.loop(); 
 }
 
 @Override
 public void onDestroy() {
  super.onDestroy();
  Log.i("pull", "onDestroy");
  
 }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值