IntentService的使用

1.为什么需要IntentService

   是LocalService的包装类,简便Service的创建,使用的是startService(),也就是访问者退出Service不会消失。

2.实现原理

步骤一:

public FirstService extends IntentService{
  public FirstService (String name){
     super(name);//需要为该Service命名
  }
  
  @Override
  protected void onHandleIntent(Intent intent) {
      //用来实现的方法的地方
  }
}        

步骤二:在AndroidManifest.xml中注册Service

<Service android:name = ".FirstService">
</Service>

步骤三:创建Intent信息发送给Service。

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Intent intent = new Intent(this,FirstService.class);
        startService(intent);//将intent发送给Service
    }
}

原理:当Service第一次接收到intent的时候,IntentService完成启动,触发一个后台线程,将intent放入队列尾部。然后在后台线程上逐个调用队列的intent触发onHandleIntent(Intent)方法。

原文地址:https://www.cnblogs.com/rookiechen/p/5272221.html