通过前两篇文章的学习,我们知道了服务的代码是默认运行在主线程里的,因此,如果要在服务里面执行耗时操作的代码,我们就需要开启一个子线程去处理这些代码。比如我们可以在 onStartCommand方法里面开启子线程来处理耗时代码。

    public int onStartCommand(Intent intent, int flags, int startId) {
        
        Thread thread = new Thread(){
            @Override
            public void run() {
                
                /**
                 * 耗时的代码在子线程里面写
                 */
                
            }
        };
        thread.start();
        
        return super.onStartCommand(intent, flags, startId);
    }

但是,我们都知道,服务一旦启动,就会一直运行下去,必须调用stopService()或者stopSelf()方法才能让服务停止下来。所以,我们来修改一下run方法

 public void run() {
                
                /**
                 * 耗时的代码在子线程里面写
                 */
                stopSelf();
                
            }

就这样,我们很容易的就在服务里面开启了一个线程,然后在代码最后面加上stopSelf();这样就可以在代码运行结束的时候,结束服务了。但是这样对于我们开发者来说,是不是有些麻烦呢,确实有点麻烦,比如你有时候忘记了开启线程呢?或者忘记了调用stopSelf()?所以,谷歌给我们一个很好的类,通过这个类我们就可以不用管这些东西,因为这个类已经帮我们实现了在子线程中操作代码了。同时,但子线程代码执行完毕,这个服务会自动销毁,不用再占用内存资源。所以,我们通过这个类,就可以不用去开启线程,也不用去销毁这个服务。因为,这个类都帮我们处理好了。这个类就是IntentService。这个类的使用和Service大同小异,但是比Service更加省心,更加方便。下面我们直接看代码吧,我习惯在代码中讲解。

布局文件就是一个按钮而已,先看布局。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    
    
    <Button 
        android:id="@+id/bt_start" 
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        />
    

</LinearLayout>
intentservice.xml

相关文章:

  • 2021-05-22
  • 2021-05-26
  • 2021-04-08
  • 2021-11-11
  • 2022-12-23
  • 2022-01-17
  • 2022-01-04
  • 2021-11-01
猜你喜欢
  • 2021-09-03
  • 2022-12-23
  • 2021-05-22
  • 2021-05-17
  • 2022-12-23
  • 2021-12-04
  • 2021-05-27
相关资源
相似解决方案