Android怎么在Service中执行耗时操作

一.Service能不能执行耗时操作?
Service是Android四大组件之一,是运行在后台的服务,可用来执行不需要在前台展示的动作,如播放音乐等;有些人可能会认为,

Service竟然是在后台运行的那不就可以用来执行耗时操作了,这样也不会影响前台页面,其实不行,因为Service也是运行在主线程,Service的onStartCommand() 和 onBind() 方法中不能执行耗时操作

所以Service是不能用来执行耗时操作的。

二.Service中开启线程
   既然Service不能执行耗时操作,那么如果我们需要在Service中执行耗时操作要怎么办呢? 那肯定是开启子线程来处理:

   例如:

            new Thread(new Runnable() {
                @Override
                public void run() {
                    
                }
            }).start();

这样确实可以,但是Android中提供了一个封装好子线程的Service给我们使用,使用起来更加简单,那就是IntentService。

三.IntentService的使用:
1.IntentService简介:

IntentService是继承Service的抽象类,在IntentService中有一个工作线程来处理耗时操作。

2.IntentService源码

我们先来看下IntentService的源码:

public abstract class IntentService extends Service {
    private volatile Looper mServiceLooper;
    private volatile ServiceHandler mServiceHandler;
    private String mName;
    private boolean mRedelivery;
 

IntentService继承Service


@Override
public void onCreate() {
    // TODO: It would be nice to have an option to hold a partial wakelock
    // during processing, and to have a static startService(Context, Intent)
    // method that would launch the service & hand off a wakelock.

    super.onCreate();
    HandlerThread thread = new HandlerThread("IntentService[" + mName + "]");
    thread.start();

    mServiceLooper = thread.getLooper();
    mServiceHandler = new ServiceHandler(mServiceLooper);

}

我们看到IntentService的onCreate方法中利用HandlerThread创建了一个循环的工作线程,然后将工作线程中的Looper对象作为参数来创建ServiceHandler消息执行者。

3.IntentService的使用:

    public class TestService extends IntentService {

        public TestService() {
            super("TestService");
        }

        @Override
        protected void onHandleIntent(@Nullable Intent intent) {
            //执行耗时操作
            
        }
    }

可以看到IntentService的使用非常简单。

Android 避免耗时操作及解决办法

1、Service的onStartCommand() 和 onBind() 方法中不能执行耗时操作
2、BroadcastReceiver的onReceive方法不能执行耗时操作,因为这个方法是在主线程执行的,耗时操作会导致UI不顺畅,超过10秒钟可能会被系统杀死
3、UI线程执行耗时操作,可以采用View.post方法来执行,或者使用Handler
4、onPause 中不适合做耗时较长的操作,Activity的跳转要先执行完前一个Activity的onPause方法,如果执行耗时操作会影响UI的显示

书到用时方恨少,纸上得来终觉浅。现在大环境不好,内卷很严重,加油。

猜你喜欢

转载自blog.csdn.net/qq_33721320/article/details/124982342