Service和IntentService区别

本文对比了Android中IntentService与Service的区别。IntentService为Service的子类,用于处理异步请求并在任务完成后自动关闭;而Service运行在主线程中,若不采取措施如创建新线程,将阻塞UI。通过实例演示了两者执行任务的不同表现。

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

Service简介:Android四大组件之一,运行在后台,没有界面,因为运行在主线程中,所以不能在其中做耗时操作,回阻塞UI,解决办法是新起Thread线程,处理耗时操作

IntentService简介:继承至Service用来处理异步请求,并且在所有任务完成后会主动关闭服务

测试:

service:

package com.example.administrator.intentservice;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;

/**
 * Created by Administrator on 2015/10/20.
 */
public class MyService extends Service {
    @Override
    public void onStart(Intent intent, int startId) {
//        new Thread(new Runnable() {
//            @Override
//            public void run() {
//
//                    Thread.sleep(3 * 1000);
//                    System.out.println("Service ok");
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
//            }
//        }).start();
        try {
            Thread.sleep(3 * 1000);
            System.out.println("Service ok");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        super.onStart(intent, startId);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return super.onStartCommand(intent, flags, startId);
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}
IntentService:
package com.example.administrator.intentservice;

import android.app.IntentService;
import android.content.Intent;

/**
 * Created by Administrator on 2015/10/20.
 */
public class MyIntentService extends IntentService {


    public  MyIntentService(){
        super("");
    }
    /**
     * 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);
    }


    @Override
    protected void onHandleIntent(Intent intent) {
        try {
            Thread.sleep(3*1000);
            System.out.println("IntentService ok");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }
}

Manifest:

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


测试:

package com.example.administrator.intentservice;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
//        startService(new Intent(this, MyIntentService.class));
//        startService(new Intent(this, MyIntentService.class));
//        startService(new Intent(this, MyIntentService.class));
        startService(new Intent(this, MyService.class));
        startService(new Intent(this, MyService.class));
        startService(new Intent(this, MyService.class));
    }
}

分别开启三个任务,结果如下:

IntentService:

Service:

 可见IntentService会主动创建线程去一次执行任务,而Service不开启新线程的情况下会阻塞UI线程!

参考:http://blog.youkuaiyun.com/lmj623565791/article/details/47143563

在 Android 开发中,`Service` `IntentService` 都是用来运行后台任务的组件,但它们之间存在显著的区别。下面是详细的对比解释: ### 1. **基本定义** - **Service**: 是一种可以在后台长时间运行的任务组件,但它本身并不开启新的线程,默认是在主线程中执行任务。 - **IntentService**: 是基于 `Service` 的扩展类,它专门为了解决耗时操作问题而设计。每次启动都会创建一个新的工作线程来完成指定的操作,并且当所有任务完成后会自动停止服务。 ### 2. **线程模型** - **Service**: 如果直接在 `Service` 中执行耗时操作(例如网络请求),可能会阻塞 UI 主线程,进而引发 ANR (Application Not Responding) 错误。 - **IntentService**: 自动开启独立的工作线程去处理耗时任务,不会影响到主界面的流畅度。 ### 3. **生命周期控制** - **Service**: 手动开始(`startService`)与手动结束(`stopSelf` 或者 `stopService`)需要开发者自行管理其生命周期。 - **IntentService**: 当所有的异步任务都完成后会自动销毁自身实例,因此不需要显式调用 stop 方法。 ### 4. **并发能力** - **Service**: 支持同时处理多个请求(取决于其实现方式),如果采用多线程则需额外注意同步问题。 - **IntentService**: 内部维护了一个工作队列 FIFO 结构,每次只从队列取出一个 intent 并顺序地在一个单独的工作者线程里依次执行完毕后再取下一个直到全部完成为止。 ### 示例代码比较 ```java // Service Example public class MyService extends Service { @Override public int onStartCommand(Intent intent, int flags, int startId){ // do something in background on main thread return super.onStartCommand(intent, flags, startId); } } // IntentService Example public class MyIntentService extends IntentService{ public MyIntentService() {super("MyIntentService");} @Override protected void onHandleIntent(Intent workIntent) { // Do the task in a worker thread. } } ``` 以上就是两者的主要差异总结了!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值