IntentService是Service类的子类,用来处理异步请求。客户端通过startService(Intent)方法传递请求给IntentService,

 IntentService通过worker thread处理每个Intent对象,执行完所有工作后自动停止Service。

 写构造方法 复写onHandleIntent()方法

IntentService执行如下操作 

   1.创建一个与应用程序主线程分开worker thread用来处理所有通过传递过来的Intent请求

   2.创建一个work queue,一次只传递一个intent到onHandleIntent()方法中,从而不用担心多线程带来的问题

   3.当处理完所有请求后自动停止服务,而不需要我们自己调用stopSelf()方法

   4.默认实现了onBind()方法,返回值为null

   5. 默认实现了onStartCommand()方法,这个方法将会把我们的intent放到work queue中,然后在onHandleIntent()中执行。

创建 MyIntentService.java 继承:android.app.IntentService


public class MyIntentService extends IntentService
{

    private static final String TAG = "MyIntentService";
    public MyIntentService()
    {
        super("MyIntentService");
    }
    @Override
    public IBinder onBind(Intent intent)
    {
        return null;
    }
    @Override
    public void onCreate()
    {
         Log.i(TAG, "MyIntentService==>>onCreate==>>线程ID:"+Thread.currentThread().getId());
        super.onCreate();
    }
    
    @Override
    public int onStartCommand(Intent intent, int flags, int startId)
    {
         Log.i(TAG, "MyIntentService==>>onStartCommand==>>线程ID:"+Thread.currentThread().getId());
        return super.onStartCommand(intent, flags, startId);
    }
    @Override
    protected void onHandleIntent(Intent intent)
    {
        
        try
        {
            Log.i(TAG, "MyIntentService==>>onHandleIntent==>>线程ID:"+Thread.currentThread().getId());
            Log.i(TAG, "文件下载中。。。。。>>文件下载线程ID:"+Thread.currentThread().getId());
            Thread.sleep(5000);
            Log.i(TAG, "文件现在完成>>文件下载线程ID:"+Thread.currentThread().getId());
        } catch (InterruptedException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        

    }
    @Override
    public void onDestroy()
    {
         Log.i(TAG, "MyIntentService==>>onDestory==>>线程ID:"+Thread.currentThread().getId());
        super.onDestroy();
    }

}

运行效果:从下图可以看出,在每次开启服务时传过去的inent,耗时操作都是有一个线程来执行处理。而所有操作排列成一个线程队列,先执行完个操作,紧接着

Android姿势点梳理-IntentService

执行下一个操作。执行完所以操作后 服务会自动onDestory操作进行销毁。

 

相关文章:

  • 2021-09-28
  • 2022-12-23
  • 2022-12-23
  • 2021-10-07
  • 2021-09-18
  • 2021-06-20
  • 2021-05-26
  • 2021-12-18
猜你喜欢
  • 2021-06-13
  • 2021-12-25
  • 2022-12-23
  • 2021-10-30
  • 2021-09-07
  • 2021-06-05
  • 2022-02-25
相关资源
相似解决方案