IntentService和Service执行子线程对比

1.为何要用子程序

服务是在主线程中执行的,直接在服务中执行耗时操作明显不可取,于是安卓官方增加了IntentService类来方便使用

在Service中执行子程序代码如下

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    new Thread(new Runnable() {
    @Override
    public void run() {
        // 处理具体的逻辑
        stopSelf();//需要自行关闭服务
        }
    }).start();
return super.onStartCommand(intent, flags, startId);
}

在IntentService中执行子程序代码如下

/**
 * 用途:用于测试IntentService类服务的特性
 * 特性:1.该服务必须覆盖onHandleIntent方法,该方法在子线程中运行
 *       2.该服务实行结束后会自动关闭,即调用onDestory( )方法
 */
public class MyIntentService extends IntentService {
    public MyIntentService() {
        //1.创建无参数构造函数,调用父类有参构造器
        super("MyIntentService");
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        Log.d(TAG,"线程ID是"+Thread.currentThread().getId());
    }

    @Override
    public void onDestroy() {
        Log.d(TAG,"IntentService关闭了");
        super.onDestroy();
    }
}
原文地址:https://www.cnblogs.com/cenzhongman/p/6400263.html