IntentService 是 Service 的子类,继承于 Service 类,用于处理后台异步请求任务。用于处理后台长时间的耗时操作,如:下载文件、播放音乐。用完自动结束。如果是普通的Service ,需要使用stopSelf()。

使用方法

IntentService 是抽象类,所以在实际使用中,我们需要创建一个 IntentService 子类来具体实现

  1. 创建 IntentService 子类,并在清单文件中注册。
  2. 在 Activity 中通过调用 startService(Intent) 方法发送任务请求。

activity_intent_service.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".IntentServiceDemo.IntentServiceActivity">
    <Button
        android:id="@+id/bt_start_service"
        android:text="开启IntentService"
        android:textSize="22sp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        />
</LinearLayout>

MyIntentService.java

public class MyIntentService extends IntentService {


    private static final String TAG = "MyIntentService";


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

    @Override
    protected void onHandleIntent(@Nullable Intent intent) {
        Log.i(TAG, "onHandleIntent: "+Thread.currentThread().getName());

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.i(TAG, "onDestroy: ");
    }
}

AndroidManifest.xml


    <service android:name=".IntentServiceDemo.MyIntentService"
            android:exported="true">

        </service>

IntentServiceActivity.java

public class IntentServiceActivity extends AppCompatActivity {
    private Button bt_start_service;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_intent_service);
        bt_start_service = (Button) findViewById(R.id.bt_start_service);
        bt_start_service.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(IntentServiceActivity.this, MyIntentService.class);
                startService(intent);
            }
        });
    }
}

在这里插入图片描述

模拟下载任务

IntentServiceActivity.java

public class IntentServiceActivity extends AppCompatActivity {
    private Button bt_start_service;
    private ProgressBar progressbar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_intent_service);
        bt_start_service = (Button) findViewById(R.id.bt_start_service);
        progressbar = (ProgressBar) findViewById(R.id.progressbar);
        bt_start_service.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //用于创建 Messenger,接收 IntentService 回复的消息
                MessengerHandler messengerHandler = new MessengerHandler(IntentServiceActivity.this);

                //模拟 whq 做下载动作
                Intent intent = new Intent(IntentServiceActivity.this, downLoadIntentService.class);
                intent.setAction(downLoadIntentService.DOWNLOAD_ACTION);
                intent.putExtra(downLoadIntentService.TEST_AUTHOR, "whq");
                //将 Messenger 传递给 IntentService,让其回复消息回来
                intent.putExtra(downLoadIntentService.TEST_MESSENGER, new Messenger(messengerHandler));
                startService(intent);
            }
        });
    }


    /**
     * 用于创建 Messenger 对象
     *
     * 静态内部类,防止内存泄漏
     */
    public static class MessengerHandler extends Handler {
        private WeakReference<IntentServiceActivity> weakReference;

        MessengerHandler(IntentServiceActivity activity) {
            weakReference = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            //msg 为 IntentService 回复的消息,包含 Bundle 等信息。
            Bundle bundle = msg.getData();
            //获取 IntentService 传递过来的 下载进度 参数
            int downloadProgressBarValue = bundle.getInt(downLoadIntentService.DOWNLOAD_PROGRESS_VALUE_KEY);

            //将下载进度设置成 ProgressBar 的进度,显示出来。
            IntentServiceActivity activity = weakReference.get();
            if (activity != null && !activity.isFinishing()) {
                activity.progressbar.setProgress(downloadProgressBarValue);
            }

        }
    }
}

activity_intent_service.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".IntentServiceDemo.IntentServiceActivity">
    <Button
        android:id="@+id/bt_start_service"
        android:text="开启IntentService"
        android:textSize="22sp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        />
    <ProgressBar
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/progressbar"
        android:max="6"
        style="@style/Widget.AppCompat.ProgressBar.Horizontal"

        />
</LinearLayout>

downLoadIntentService.java

public class downLoadIntentService extends IntentService {

    private static final String TAG = "downLoadIntentService";

    public static final String DOWNLOAD_ACTION = "DOWNLOAD_ACTION";
    public static final String READ_ACTION = "READ_ACTION";
    public static final String TEST_AUTHOR = "TEST_AUTHOR";
    public static final String TEST_MESSENGER = "TEST_MESSENGER";
    public static final String DOWNLOAD_PROGRESS_VALUE_KEY = "DOWNLOAD_PROGRESS_VALUE";



    public downLoadIntentService() {
        super(TAG);
    }

    @Override
    protected void onHandleIntent(@Nullable Intent intent) {
        Log.i(TAG, "onHandleIntent: "+Thread.currentThread().getName());
        if (intent != null) {
            final String action = intent.getAction();
            String author = intent.getExtras().getString(TEST_AUTHOR);

            //模拟下载动作
            if (DOWNLOAD_ACTION.equals(action)) {
                for (int i = 0; i <= 6; i++) {
                    try {
                        //线程等待1s,模拟耗时操作
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    Log.e(TAG, author + " " + action + " " + i);
                    //获取从 Activity 传入的 Messenger
                    Messenger messenger = (Messenger) intent.getExtras().get(TEST_MESSENGER);
                    //新建消息,设置下载进度参数
                    Message msg = new Message();
                    Bundle bundle = new Bundle();
                    bundle.putInt(DOWNLOAD_PROGRESS_VALUE_KEY, i);
                    msg.setData(bundle);
                    try {
                        //回复消息
                        messenger.send(msg);
                    } catch (RemoteException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        
    }

    @Override
    public int onStartCommand( Intent intent, int flags, int startId) {
        Log.i(TAG, "onStartCommand: ");
        return super.onStartCommand(intent, flags, startId);
    }
}


AndroidManifest.xml

        <service android:name=".IntentServiceDemo.downLoadIntentService"
            android:exported="true">

        </service>

在这里插入图片描述
在这里插入图片描述
点击一次就会调用onStartCommand一次。

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐