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)方法。
本文深入解析了Android中的IntentService,解释了其存在的必要性,即作为LocalService的包装类,简化了Service的创建流程。通过具体代码示例展示了IntentService的实现步骤,并详细阐述了其工作原理,包括如何在后台线程中处理Intent队列。
831

被折叠的 条评论
为什么被折叠?



